Using the latest versions of AutoMapper, you can do something like the following:
config.CreateMap<Product, ProductViewModel>() .ForMember(q => q.Categories, option => option.Ignore()); config.CreateMap<ProductWithCategories, ProductViewModel>() .ConstructUsing(s => AutoMapper.Mapper.Map<ProductViewModel>(s.Product)) .ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories)) .ForAllOtherMembers(o => o.Ignore();
ConstructUsing () is used to generate and populate the base class from a nested child [ren] source. If you have more than one such nested child, you need to make several display calls in order to map each of them to the instance generated by the first call to Map () .. ForAllOtherMembers () relatively recently (if you do not have one, get a newer version AutoMapper.) Unfortunately, it is a little unsafe, as if you add target elements that will need to be mapped, but forget to update the map, the configuration check will not catch it.
source share