0

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?

ngruson
  • 1,176
  • 1
  • 13
  • 25
  • Please [edit] your question to include the full automapper configuration you have and the example code on how you transform the object as a [mcve]. – Progman May 01 '20 at 11:35
  • Generally `ProjectTo` and inheritance don't mix. But that shouldn't stop you from [trying](https://docs.automapper.org/en/latest/Mapping-inheritance.html#as) :) – Lucian Bargaoanu May 01 '20 at 11:55

1 Answers1

2

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.

ngruson
  • 1,176
  • 1
  • 13
  • 25