简体   繁体   中英

How to Unpack a Parent object into a child object using Automapper?

I want to unpack a parent object using automapper and create a new child object with it:

parent:

public class Parent
{
    public Child Child {get;set;}
}


public class Child
{
    //stuff
}

First attempt at mapping:

Mapper.CreateMap<Parent, Child>()
    .ForMember(dest => dest, opt => opt.MapFrom(src => src.Parent.Child);

Error message:

    Custom configuration for members is only supported for top-level individual members on a type.

That makes sense so I tried to resolve it myself:

.BeforeMap((src, dest) =>
{
    dest = new Child();
});

This didn't work for the same reason, even though I would argue that I am resolving the object.

So, How do I resolve the child object, so that I can create it using automapper?

Assuming you want the same object reference as the result:

Mapper.CreateMap<Parent, Child>()
    .ConvertUsing(par => par.Child);

Here you're telling AutoMapper that you know how to do the entire mapping, which in this case just means returning the inner Child property.

Note that the following is true if you go this route:

Parent p = new Parent();

Child c = Mapper.Map<Child>(p);

object.ReferenceEquals(parent.Child, c); // true

If you wanted to copy the entire Child instance into a brand new instance, you could set up a mapping from ChildChild and then call Mapper.Map inside of the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM