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