[英]Automapper map from one object to nested objects
What is the best way to map inner objects with Automapper 2.0使用 Automapper 2.0 映射内部对象的最佳方法是什么
Use the solution in this question (Automapper 1.0)使用此问题中的解决方案(Automapper 1.0)
Create a Custom Value Resolvers创建自定义值解析器
? ?
public class DTOObject { // MainObject public int Id { get; set; } public string Name { get; set; } // SubObject (TopObject) public string TopText { get; set; } public string TopFont { get; set; } // SubObject (BottomObject) public string BottomText { get; set; } public string BottomFont { get; set; } } public class MainObject { public int Id { get; set; } public string Name { get; set; } public SubObject TopObject { get; set; } public SubObject BottomObject { get; set; } } public class SubObject { public string SubPropText { get; set; } public string SubPropFont { get; set; } }
Custom Value Resolvers自定义值解析器
public class CustomResolver : ValueResolver<DTOObject, SubObject>
{
protected override SubObject ResolveCore(DTOObject source)
{
return Mapper.Map<DTOObject, SubObject>(source);
}
}
For me it was possible to use just MapFrom (without ResolveUsing what gives you a chance to use this mapping with IQueryable extensions).对我来说,可以只使用 MapFrom(没有 ResolveUsing 什么让你有机会使用带有 IQueryable 扩展的映射)。 So you will get the following in the Automapper configuration:
因此,您将在 Automapper 配置中获得以下内容:
Mapper.CreateMap<DTOObject, SubObject>()
.ForMember(dest => dest.SubPropText, opt => opt.MapFrom(x => x.BottomText))
.ForMember(dest => dest.SubPropFont, opt => opt.MapFrom(x => x.BottomFont));
Mapper.CreateMap<DTOObject, MainObject>()
.ForMember(dest => dest.SubPart, opt => opt.MapFrom(x => x));
I ended up creating my own value resolvers for any SubObjects of MainObject
that come from DTOObject
.我最终为来自
DTOObject
MainObject 的MainObject
创建了自己的值解析器。
public class PartResolver<T> : ValueResolver<DTOObject, T>
{
protected override T ResolveCore(DTOObject source)
{
return Mapper.Map<T>(source);
}
}
Then in my Automapper config I create a map from the DTOObject
to SubObject
and use the ValueResolver to map that object into the MainObject
然后在我的
DTOObject
配置中,我创建了一个从DTOObject
到SubObject
映射,并使用 ValueResolver 将该对象映射到MainObject
Mapper.CreateMap<DTOObject, SubObject>();
Mapper.CreateMap<DTOObject, MainObject>()
.ForMember(dest => dest.SubPart, opt => opt.ResolveUsing<PartResolver<SubObject>>());
ResolveUsing is not available with latest version of AutoMapper. ResolveUsing不适用于最新版本的 AutoMapper。 So only option left is to use MapFrom .
所以剩下的唯一选择是使用MapFrom 。 (use @ZedRoth solution).
(使用@ZedRoth 解决方案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.