AutoMapper - mapping to interface properties

1.3k views Asked by At

I'm using AutoMapper's queryable extensions to map Entity Framework Core entities to DTOs.

var appleTrees = context.AppleTrees
  .ProjectTo<AppleTreeDto>(mapper.ConfigurationProvider);

Some DTOs have interface properties like this:

public IFruitTreeDto
{
  List<IFruitDto> Fruits { get; set; }
}

public class AppleDto : IFruitDto
{
  ...
}

public AppleTreeDto : IFruitTreeDto
{
  public List<IFruitDto> Fruits { get; set; }
}

Mapping configuration sits in an AutoMapper profile:

CreateMap<EF.AppleTree, AppleTreeDto>();
CreateMap<EF.Apple, AppleDto>();

Currently, I'm getting an exception 'Missing map from Apple to IFruitDto. Create using CreateMap'. After I added that map, I was getting an exception that IFruitDto could not be instantiated (which makes sense, it's an interface, not a class).

How do I tell Automapper to use AppleDto for the Fruits collection when mapping to AppleTreeDto? What is the optimal way of doing so? Am I supposed to write a type converter for every interface property?

1

There are 1 answers

0
ngruson On

Thank you Lucian for pointing me in the right direction! Got it working by making this change:

CreateMap<EF.Apple, IAppleDto>().As<AppleDto>();

My object model is in fact a bit more complex, I actually will have multiple implementations of IAppleDto in the system, so I don't know if this fix will hold up, but for now it's working.