且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用AutoMapper映射目标对象和源对象中的子对象?

更新时间: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成员的映射Product-> ProductViewModel
  • 定义映射CategoryCategoryViewModel
  • 定义用于映射类别的映射ProductWithCategories-> ProductViewModel,然后在后映射中映射Product:

  • Define a mapping Product -> ProductViewModel used to flatten the members of Product
  • Define a mapping Category 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));