Can I use inheritance mapping in AutoMapper (v2.2) for maps with the same Source type but different Destination types?
I have this basic situation (the real classes
Unfortunately in this case, AutoMapper seems to be registering only one child class mapping per source type, the last one (ViewModelB). This was probably designed to work with parallel hierarchies, not with a single source type.
To work around this, you can encapsulate the common mappings in an extension method:
public static IMappingExpression MapBaseViewModel(this IMappingExpression map)
where TDestination : BaseViewModel {
return map.ForMember(x => x.CommonProperty, y => y.MapFrom(z => z.Property1));
}
And use it in the individual subclass mappings:
Mapper.CreateMap()
.MapBaseViewModel()
.ForMember(x => x.PropertyA, y => y.MapFrom(z => z.Property2));
Mapper.CreateMap()
.MapBaseViewModel()
.ForMember(x => x.PropertyB, y => y.MapFrom(z => z.Property3));