I have one main interface that other interfaces inherit from. I would like the main automapper map to switch and return another relevant defined mapping depending on the object type.
For example, call the main interface IGroup:
public interface IGroup {...}
And then make some more interfaces that inherit from that:
public interface IFamily : IGroup {...}
public interface IFriends : IGroup {...}
public interface INeighbours : IGroup {...}
I define relevant mappings for each inherited group:
CreateMap<IFamily, GroupListView>() ...etc
On the main IGroup map, I would like to switch so that if I have a collection of IGroup it returns the relevant mapping for each item.
I have tried
CreateMap<IGroup, GroupListView>()
.Include<IFamily, GroupListView>()
.Include<IFriends, GroupListView>()
.Include<INeighbours, GroupListView>()
.ConstructUsing((IGroup group, ResolutionContext context) =>
{
switch (group)
{
case IFamily family:
return context.Mapper.Map<IFamily, GroupListView>(family);
case IFriends friends:
return context.Mapper.Map<IFriends, GroupListView>(friends);
case INeighbours neighbors:
return context.Mapper.Map<INeighbours, GroupListView>(neighbors);
default:
throw new InvalidOperationException("Unknown group type: " + group.GetType().FullName);
}
})
But validation complains that there are unmapped members on the IGroup interface because I’m not actually defining anything.
If I define anything after or opt.Ignore, then it overrides the ConstructUsing result.
What would be even better is if instead of throwing an error on unrecognised IGroup type, it returned a default map for IGroup.
Many thanks.