自动映射器-从源子对象到目标的映射包括父值

在尝试从源对象的子属性映射整个目标对象时,我目前遇到问题。类似于此处所述:Automapper - How to map from source child object to destination

我已经使用了上面链接中描述的.ConstructUsing方法,但是我看到了一些奇怪的行为,其中输出的映射对象从父级而不是子级获取值。

我在此处演示了该问题:https://dotnetfiddle.net/OdaGUr

这是我的代码是否有问题,是否应该使用其他方法来实现我要执行的操作,或者这是AutoMapper的错误?

编辑:

public static void Main()
{
    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Child1,Child2>();
        cfg.CreateMap<Parent,Child2>().ConstructUsing((src,ctx) => ctx.Mapper.Map<Child2>(src.Child1));   
     });

    var mapper = config.CreateMapper();

    var parent = new Parent{
        Id = 1,Child1 = new Child1 {
            Id = 2
        }
    };

    var child2 = mapper.Map<Parent,Child2>(parent);
    Console.WriteLine(child2.Id); // Returns 1. Expect this to be 2 from Parent.Child1
}

public class Parent
{
    public int Id {get;set;}
    public Child1 Child1 {get;set;}
}

public class Child1
{
    public int Id {get;set;}
}

public class Child2
{
    public int Id {get;set;}
}
iCMS 回答:自动映射器-从源子对象到目标的映射包括父值

ConstructUsing()用于创建目标对象,该值应存储在该目标对象中。在您的情况下,您将返回一个Child2值设置为{{1 }}(由Id行返回)。

但是,在创建对象之后,仍将应用默认映射。这意味着2的值将保存在ctx.Mapper.Map<Child1,Child2>(src.Child1)属性中,因为该属性的名称匹配(Parent.Id)。因此,Child2.Id的初始值将被"Id"对象中的值2替换。

根据您要执行的操作,可能需要使用1来配置有关如何映射属性值的特殊处理。一个例子是:

Parent
本文链接:https://www.f2er.com/2146730.html

大家都在问