1
votes

I have an ASP.Net Core C# application & using AutoMapper

DTO

public class MovieTO
{
   public int Id { get; set;}

   public IEnumerable<TicketTO> Tickets { get; set;}
}


public class TicketTO
{
   public string Prop1{ get; set;}
   public string Prop2{ get; set;}
   public string Prop3{ get; set;}
   public string Prop4{ get; set;}
}

Domain Entity

public class Movie
{
   public int Id { get; set;}

   public IEnumerable<BasicTicket> Tickets { get; set;}
}

 public class BasicTicket
{

}

 public class RegularTicket : BasicTicket
{
   public string Prop1{ get; set;}
   public string Prop2{ get; set;}
}

 public class SpecialTicket : BasicTicket
{
   public string Prop3{ get; set;}
   public string Prop4{ get; set;}
}

AutoMapper Configuration

 public class AppObjectsMapper
{
    private readonly IMapper _mapper;

    public ObjectsMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {

            cfg.CreateMap<TicketTO, RegularTicket>();
            cfg.CreateMap<TicketTO, SpecialTicket>();

            cfg.CreateMap<MovieTO, Movie()

        });
        _mapper = config.CreateMapper();
    }


    public Movie MapToEntity(MovieTO movie)
    {

        if(movie.IsSpecial)
        {
            //#Line1
            _mapper.Map<IEnumerable<TicketTO>, IEnumerable<SpecialTicket>>(movie.Tickets); 
        }
        else
        {
             //#Line2
            _mapper.Map<IEnumerable<TicketTO>, IEnumerable<RegularTicket>>(movie.Tickets);
        }
        return _mapper.Map<MovieTO, Movie>(eventDetail);
    }

       }

When the mapper is called at #line1 or #line2, it throws the below run time error.

Error mapping types. Mapping types: IEnumerable1 -> IEnumerable1 System.Collections.Generic.IEnumerable1[[TicketTO, app.DTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IEnumerable1[[Domain.SpecialTicket, myapp.domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

How to typecast/map this ?

Thanks!

1
Not directly related to your error but what's the point of this: IEnumerable<BasicTicket> and BasicTicket? If you think you can shove both types of tickets into IEnumerable<BasicTicket> and read them out, it's not possible. This could be related to the issue but only by design.CodingYoshi
Actually I read more of your code and my comment above is now directly related to the issue because of what you're doing in the method MapToEntity.CodingYoshi
Call AssertConfigurationIsValid. And look at the full error message.Lucian Bargaoanu
@CodingYoshi, Please note I have NoSql in Db (Model - Movie)Kgn-web

1 Answers

3
votes

Actually your are missing some of the configuration here which the exception actually clearly says. So just read the exception and add the mapping that is missing like:

            cfg.CreateMap<TicketTO, BasicTicket>();

That should work. Best regards Robert