自动映射器-使用集合映射对象 [英] Auto mapper - Mapping objects with collections
本文介绍了自动映射器-使用集合映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用自动映射器,我需要映射以下类的对象
using Auto Mapper, I need to Map objects of following classes
public class RemoteClass
{
public IEnumerable<RemoteDetails> collection{get; set;};
public int RemoteFieldA{get; set;}
public int RemoteFieldB{get; set;}
}
public class LocalClass
{
public IEnumerable<LocalDetails> collection{get; set;};
public int LocalFieldA{get; set;}
public int LocalFieldB{get; set;}
}
对此我应该如何配置和映射?
What should be my configration and mapping for this ?
推荐答案
只需定义 RemoteDetails
和 LocalDetails
之间的映射.AutoMapper非常聪明,可以处理他知道如何映射的类型集合.假设这两个类具有字段C:
Just define mapping between RemoteDetails
and LocalDetails
. AutoMapper is smart enough to deal with collections of types which he knows how to map. Assume these two classes have field C:
Mapper.CreateMap<RemoteDetails, LocalDetails>()
.ForMember(ld => ld.LocalFieldC, opt => opt.MapFrom(rd => rd.RemoteFieldC));
Mapper.CreateMap<RemoteClass, LocalClass>()
.ForMember(lc => lc.LocalFieldA, opt => opt.MapFrom(rc => rc.RemoteFieldA))
.ForMember(lc => lc.LocalFieldB, opt => opt.MapFrom(rc => rc.RemoteFieldB));
使用这些映射,您可以从RemoteClass映射到LocalClass:
With these mappings you can map from RemoteClass to LocalClass:
RemoteClass remote = new RemoteClass {
RemoteFieldA = 42,
RemoteFieldB = 100,
collection = new [] {
new RemoteDetails { RemoteFieldC = "Foo" },
new RemoteDetails { RemoteFieldC = "Bar" }
}
};
var local = Mapper.Map<LocalClass>(remote);
结果:
这篇关于自动映射器-使用集合映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文