【发布时间】: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 => src.Id, opt => opt.Ignore())忽略Id,然后它会从Child1 获取它,但我不太明白为什么它在没有这个的情况下选择Parent 而不是Child1? -
这就是它应该做的 :) 你的意思是
ConvertUsing,而不是ConstructUsing。检查the execution plan。 -
@LucianBargaoanu 对不起,我想我很困惑。在我的问题演示中,我正在使用
ConstrustUsing:cfg.CreateMap<Parent, Child2>().ConstructUsing((src, ctx) => ctx.Mapper.Map<Child1, Child2>(src.Child1));这不对吗?
标签: c# asp.net-core automapper automapper-9