ConfigureAutomapper to map contents of collection-property, but use destination collection object
I have a class
class A
{
public A()
{
CollectionProp = new List<B>();
}
public ICollection<B> CollectionProp {get; private set;}
}
Lets say that I want to map from A -> A, as a cloning mechanism, but开发者_如何学Go I dont want AutoMapper to attempt to create the CollectionProp, it should just use the CollectionProp that exists in the destination object (created by the constructor), but clone all the 'B' objects from A into the new instance of A.
How do I do this.. So far I have:
Mapper.CreateMap<A, A>()
.ForMember(dest => dest.CollectionProp, opt => opt.MapFrom(e => e.CollectionProp));
Which appears to use the CollectionProp from the newly created object, but its not filling up its elements.
What am I missing?
Thanks
This one worked for me
Mapper.CreateMap<A, A>()
.ConvertUsing((s) => {
var d = new A();
d.CollectionProp.AddRange(s.CollectionProp);
return d;
});
Ok. This one actually clones the Bs
Mapper.CreateMap<B,B>();
Mapper.CreateMap<A, A>()
.ConvertUsing(s => {
var d = new A();
s.CollectionProp.ToList()
.ForEach(b => d.CollectionProp.Add(Mapper.Map<B,B>(b)));
return d;
});
精彩评论