简体   繁体   English

如何使用 Automapper 将父对象解包为子对象?

[英]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:我想使用 automapper 解压缩父对象并用它创建一个新的子对象:

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?那么,如何解析子对象,以便可以使用 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.在这里,您告诉 AutoMapper 您知道如何进行整个映射,在这种情况下,这仅意味着返回内部Child属性。

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:如果你想将整个Child实例复制到一个全新的实例中,你可以从ChildChild设置一个映射,然后在ConvertUsing调用中调用Mapper.Map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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