0
votes

I'm attempting to map to a custom type property in a DTO from one of a few different navigation properties of a source entity, conditional on which of them is not null.

Simplified version (some of the conditional maps removed):

 CreateMap<MyDTO, MyEntity>()
                  .ForMember(dest => dest.Order,
                  opt =>
                  {
                  opt.MapFrom(src => src.OrderType1 != null ? src.OrderType1 :
                  src.OrderTypeA.OrderType1 != null ? OrderTypeA.OrderType1 :
                  src.OrderType2 != null ? src.OrderType2 : null
                  ));

It won't compile because OrderType2 entity is of a different type then OrderType1

Type of conditional expression cannot be determined because there is no implicit conversion between 'OrderType1' and 'OrderType2'

I've tried creating an empty type, having both entity types inherit from this then casting to the base type in the conditional expression. This throws an exception because it has unmapped types for all properties.

Assume I could refactor to use the base class on navigation properties throughout and create a mapping from base to derived for each entity to get this to work but feel it would introduce too many changes.

Is there an alternative approach to this using Automapper, or another way to resolve the issue - have multiple conditions that can return different source types to be mapped?

1
How about making them to implement an interface?dcg
Is there a solution in Automapper to resolve the issue this error has nothing to do with Automapperdcg
Thanks, have edited to ask for alternative solution in Automapper, or a way to resolve the issue.JMP
An interface will cause issues as the types have mostly different properties (resolved through mapping) . Having said, it is probably worth me experimenting further on this.JMP
That's the idea with the interface, it contains only those common properties.dcg

1 Answers

0
votes

It seems too simple but got it working by casting to object within the conditional:

 CreateMap<MyDTO, MyEntity>()
                  .ForMember(dest => dest.Order,
                  opt =>
                  {
                  opt.MapFrom(src => src.OrderType1 != null ? src.OrderType1 :
                  src.OrderTypeA.OrderType1 != null ? OrderTypeA.OrderType1 :
                  src.OrderType2 != null ? (object)src.OrderType2 : null
                  ));

This runs and creates all the required maps.