AutoMapper mapping base class and projection

136 Views Asked by At

How do I map this:

public class Domain_1
{
   public DomainType DomainType { get; set; }
   public Domain_2 Domain2 { get; set; }
   public Domain_3 Domain3 { get; set; }
}

to:

public abstract class DTOBase
{
   // properties from Domain_1
}

public class DTO_1 : DTOBase
{
   // properties from Domain_2
}

public class DTO_2 : DTOBase
{
   // properties from Domain_3
}

Ideally,the Domain design should be same as the DTO but I can't due to EF6 and existing database restrictions.

Currently what I have right now is:

this.CreateMap<Domain_1, DTOBase>()
    .ConstructUsing(SomeDTOCreatorFactoryMethod);

this.CreateMap<Domain_2, DTO_1>();

What SomeDTOCreatorFactoryMethod does is it creates the DTO based on the DomainType.

This works fine but I wanted to do some projection something like:

var domain_Db = dbContext.Domain1.Where(d => d.Id == 1).ProjectTo<DTOBase>.SingleOrDefault();
// var result = _mapper.Map<Domain1, DTOBase>(domain_Db);

Its throwing an error that cannot instantiate an abstract class. I understand the error but how I can use the factory method in order to create the DTO?

And what if I have to use a custom resolver on certain properties? I know this is not supported but is there a workaround?

0

There are 0 best solutions below