更新时间:2022-05-29 23:15:01
与OP进行了一些讨论之后,事实证明,他的主要需求是快速将源对象内部的子对象/嵌套对象映射到扁平化的目标对象.他不想为目的地的每个属性编写一个映射.
After some discussion with OP, it turns out his main need is to quickly map a child/nested object inside the source object to the flattened destination object. He does not want to write a mapping for every property of the destination.
这是实现此目标的一种方法:
Here is a way to achieve this:
Product
-> ProductViewModel
Category
到CategoryViewModel
定义用于映射类别的映射ProductWithCategories
-> ProductViewModel
,然后在后映射中映射Product
:
Product
-> ProductViewModel
used to flatten the members of ProductCategory
to CategoryViewModel
Define a mapping ProductWithCategories
-> ProductViewModel
that maps the categories, and then in the aftermap, map the Product
:
config.CreateMap<ProductWithCategories, ProductViewModel>()
.ForMember(q => q.Id, option => option.Ignore()) // flattened in AfterMap
.ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories))
.AfterMap((src, dst) => Mapper.Map(src.Product, dst));
config.CreateMap<ProductWithCategories, ProductViewModel>()
.ForMember(q => q.Id, option => option.Ignore()) // flattened in AfterMap
.ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories))
.AfterMap((src, dst) => Mapper.Map(src.Product, dst));