[英]AutoMapper - How to map entire object from source's single property?
Creating a map for two types where the destination type shares some of the source's properties is really straightforward:为目标类型共享一些源属性的两种类型创建 map 非常简单:
CreateMap<Type1, Type2>().IgnoreAllNonExisting();
But what if I have Type1
inside other property?但是如果我在其他属性中有
Type1
怎么办? Let's call it - ParentType
.我们称之为 -
ParentType
。 Currently, I do this目前,我这样做
CreateMap<ParentType, Type2>().IgnoreAllNonExisting()
.ForMember(t => t.Prop1, opt => opt.MapFrom(l => l.Child.Prop1))
.ForMember(t => t.Prop2, opt => opt.MapFrom(l => l.Child.Prop2))
.ForMember(t => t.Prop3, opt => opt.MapFrom(l => l.Child.Prop3))
The Child
property is of type Type1
. Child
属性的类型为Type1
。 Because of this, I have to map every property separately.因此,我必须分别对每个属性进行 map。 Is there a better approach for such cases?
对于这种情况有更好的方法吗?
As @Lucian already suggested, use IncludeMembers(p => p.Child)
pointing to a child object which also should be used when mapping to destination object:正如@Lucian 已经建议的那样,使用指向子 object 的
IncludeMembers(p => p.Child)
映射到目标 object 时也应该使用它:
CreateMap<Type1, Type2>();
CreateMap<ParentType, Type2>()
.IncludeMembers(p => p.Child);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.