使用Automapper,我需要映射以下类的对象
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;}
}
我的配置和映射应该是什么?
答案 0 :(得分:7)
只需定义RemoteDetails
和LocalDetails
之间的映射即可。 AutoMapper足够聪明,可以处理他知道如何映射的类型集合。假设这两个类有字段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:
RemoteClass remote = new RemoteClass {
RemoteFieldA = 42,
RemoteFieldB = 100,
collection = new [] {
new RemoteDetails { RemoteFieldC = "Foo" },
new RemoteDetails { RemoteFieldC = "Bar" }
}
};
var local = Mapper.Map<LocalClass>(remote);
结果: