Reputation: 90
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 ?
Upvotes: 2
Views: 3285
Reputation: 236248
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));
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);
Result:
Upvotes: 7