简体   繁体   English

AutoMapper - 如何从源的单一属性 map 整个 object?

[英]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.

相关问题 使用 Automapper 到 map 从对象列表到单个 object 使用来自源的属性值 - Use Automapper to map from a list of objects to a single object using property values from source Automapper - 如何从源子对象映射到目标 - Automapper - How to map from source child object to destination 如何使用AutoMapper映射多个对象中的单个对象? - How to map a single object from multiple ones, using AutoMapper? AutoMapper将源对象上的单个列表映射到目标对象上的两个列表 - AutoMapper Map single list on source object into two lists on destination object 自动映射器:将类型X的属性从源对象映射到目标对象,并将等值属性映射为类型X - Automapper: Map property of type X from source object to destination object with equivlanet properties to type X 如何使用 AutoMapper 将单个属性映射到集合的每个元素的属性? - How to map a single property to each element's property of a collection using AutoMapper? 自动映射器,将Source映射到Destination的属性 - Automapper, map Source to property of Destination 自动映射 - 当源对象具有值的属性时,不映射 - Automapper - Don't map when a source object has a property with a value 如何在 Automapper 中从源进行部分映射 - How to do a partial map from source in Automapper 如何使用AutoMapper将目标对象与源对象中的子对象进行映射? - How to use AutoMapper to map destination object with a child object in the source object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM