1

Need some expert advice on this Automapper problem I'm trying to solve.

I have three classes, an entity, a base, and a derived class.

public class MyEntity
{
   public string RefNumber {get;set;}
}

public class MyBaseClass
{
    public string UserName {get;set;}
}

public class MyDto : MyBaseClass
{
    public string RefNumber {get;set;}
}

public class MyDto2 : MyBaseClass
{
    public string InvoiceNumber {get;set;}
}  

Based on Automapper docs, I have created the following mapping

CreateMap<MyEntity, MyBaseClass>()
           .ForPath(d => d.UserName , opt => opt.MapFrom(src => src.UserName))
           .IncludeAllDerived();

CreateMap<MyEntity, MyDto>()
           .ForMember(d => d.RefNumber, opt => opt.MapFrom(src => src.RefNumber));

At this point I can easily map either MyDto or MyBaseClass:

       var entity = GetEntity();

       var myMappedDto = _mapper.Map<MyDto>(entity);

       var myMappedBase = _mapper.Map<MyBaseClass>(entity);

Both myMappedDto and myMappedBase return me exactly what I expect, however, the real requirement here is to map entity related Dto (MyDto, MyDto2, etc) AND also return the props from MyBaseClass.

Hopefully that makes sense...appreciate the input.

 public async Task<MyBaseClass> GetAsync(int id)
    {
        var entity = await GetEntity(jobId);

        //based on entity programatically choose the related Dto and map that 
        var mappedThing = _mapper.Map<MyDto>(entity);

        //OR map the base class and somehow magically include the relevant DTO props
        var mappedThing = _mapper.Map<MyBaseClass>(entity);

        return mappedThing;
    }
Tango Down
  • 77
  • 9
  • http://docs.automapper.org/en/latest/Mapping-inheritance.html – Lucian Bargaoanu Jan 28 '20 at 16:37
  • Thanks I used those docs to create what I have atm – Tango Down Jan 28 '20 at 16:56
  • The docs explain that, when mapping to a base type, the derived type is chosen by the source type. But you have only one source type, so AM cannot do that for you. So you have to choose the destination type somehow. There are many questions about this and a few ways to do it. – Lucian Bargaoanu Jan 30 '20 at 13:23

0 Answers0