自动映射器从一个对象映射到嵌套对象 [英] Automapper map from one object to nested objects
本文介绍了自动映射器从一个对象映射到嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Automapper 2.0映射内部对象的最佳方法是什么
What is the best way to map inner objects with Automapper 2.0
-
在此问题中使用解决方案(Automapper 1.0)
Use the solution in this question (Automapper 1.0)
创建自定义值解析器
?
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; }
}
自定义值解析器
public class CustomResolver : ValueResolver<DTOObject, SubObject>
{
protected override SubObject ResolveCore(DTOObject source)
{
return Mapper.Map<DTOObject, SubObject>(source);
}
}
推荐答案
我最终为来自DTOObject
的MainObject
的所有子对象创建了自己的值解析器.
I ended up creating my own value resolvers for any SubObjects of MainObject
that come from DTOObject
.
public class PartResolver<T> : ValueResolver<DTOObject, T>
{
protected override T ResolveCore(DTOObject source)
{
return Mapper.Map<T>(source);
}
}
然后在我的Automapper配置中创建一个从DTOObject
到SubObject
的映射,并使用ValueResolver将该对象映射到MainObject
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
Mapper.CreateMap<DTOObject, SubObject>();
Mapper.CreateMap<DTOObject, MainObject>()
.ForMember(dest => dest.SubPart, opt => opt.ResolveUsing<PartResolver<SubObject>>());
这篇关于自动映射器从一个对象映射到嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文