如何使用AutoMapper映射目标对象和源对象中的子对象? [英] How to use AutoMapper to map destination object with a child object in the source object?
问题描述
我有这样的源对象和目标对象:
I have the source and destination objects like this:
class ProductWithCategories // Source class
{
public Product Product { get; set; } // Product is an EF entity class
public IEnumerable<Category> Categories { get; set; }
}
class ProductViewModel // Dest class
{
public int Id { get; set; }
// Other properties with the same name as Product class
public IEnumerable<CategoryViewModel> Categories { get; set; }
}
所以,我需要将source.Product
的值映射到dest
,然后将source.Categories
的值映射到dest.Categories
.可以使用AutoMapper吗?
So, my need is to map the values of source.Product
into dest
, and then source.Categories
into dest.Categories
. Is it possible with AutoMapper?
我已经尝试过了,但是当它失败时我并不感到惊讶:
I have tried this and I was not surprised when it failed:
config.CreateMap<ProductWithCategories, ProductViewModel>()
.ForMember(q => q, option => option.MapFrom(q => q.Product))
.ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories));
这是我收到的例外情况:
Here is the exception I received:
[AutoMapperConfigurationException:成员的自定义配置为 仅支持类型上的顶级个人成员.]
[AutoMapperConfigurationException: Custom configuration for members is only supported for top-level individual members on a type.]
推荐答案
与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
- 定义映射
Category
到CategoryViewModel
-
定义用于映射类别的映射
ProductWithCategories
->ProductViewModel
,然后在后映射中映射Product
:
- Define a mapping
Product
->ProductViewModel
used to flatten the members of Product - Define a mapping
Category
toCategoryViewModel
Define a mapping
ProductWithCategories
->ProductViewModel
that maps the categories, and then in the aftermap, map theProduct
:
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));
这篇关于如何使用AutoMapper映射目标对象和源对象中的子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!