c# - How to Unpack a Parent object into a child object using Automapper? -


i want unpack parent object using automapper , create new child object it:

parent:

public class parent {     public child child {get;set;} }   public class child {     //stuff } 

first attempt @ mapping:

mapper.createmap<parent, child>()     .formember(dest => dest, opt => opt.mapfrom(src => src.parent.child); 

error message:

    custom configuration members supported top-level individual members on type. 

that makes sense tried resolve myself:

.beforemap((src, dest) => {     dest = new child(); }); 

this didn't work same reason, though argue resolving object.

so, how resolve child object, can create using automapper?

assuming want same object reference result:

mapper.createmap<parent, child>()     .convertusing(par => par.child); 

here you're telling automapper know how entire mapping, in case means returning inner child property.

note following true if go route:

parent p = new parent();  child c = mapper.map<child>(p);  object.referenceequals(parent.child, c); // true 

if wanted copy entire child instance brand new instance, set mapping childchild , call mapper.map inside of convertusing call:

mapper.createmap<parent, child>()     .convertusing(par => mapper.map<child>(par.child));  mapper.createmap<child, child>();  parent p = new parent {     child = new child { name = "kid" } };  var ch = mapper.map<child>(p);  object.referenceequals(parent.child, ch); // false 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -