【问题标题】:Automapper - Mapping from source child object to destination is including parent valuesAutomapper - 从源子对象到目标的映射包括父值
【发布时间】:2020-06-12 13:09:14
【问题描述】:

我目前在尝试从源对象上的子属性映射整个目标对象时遇到问题。类似于此处描述的内容: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;}
}

【问题讨论】:

  • @LucianBargaoanu 抱歉,我应该看哪一部分?对我来说,在我给出的示例中,AutoMapper 应该从 Child1 中提取所有属性值,而从 Parent 中不提取任何属性值。我可以看到我可以在调用.ConstructUsing 之前使用ForMember(src =&gt; src.Id, opt =&gt; opt.Ignore()) 忽略Id,然后它会从Child1 获取它,但我不太明白为什么它在没有这个的情况下选择Parent 而不是Child1?
  • 这就是它应该做的 :) 你的意思是ConvertUsing,而不是ConstructUsing。检查the execution plan
  • @LucianBargaoanu 对不起,我想我很困惑。在我的问题演示中,我正在使用ConstrustUsingcfg.CreateMap&lt;Parent, Child2&gt;().ConstructUsing((src, ctx) =&gt; ctx.Mapper.Map&lt;Child1, Child2&gt;(src.Child1)); 这不对吗?

标签: c# asp.net-core automapper automapper-9


【解决方案1】:

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

但是,在创建对象后,仍将应用默认映射。这意味着Parent.Id 值将保存在Child2.Id 属性中,因为属性的名称匹配("Id")。因此,2 的初始值将替换为来自Parent 对象的值1

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

.ForMember(dest => dest.Id, src => src.MapFrom(it => it.Child1.Id))

【讨论】:

  • 为解释干杯,我会看看这样做。还编辑了我的帖子以包含我的演示中的代码。
猜你喜欢
  • 2017-06-19
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2018-06-18
  • 1970-01-01
  • 2011-07-17
  • 2022-01-02
相关资源
最近更新 更多