[英]Automapper - Mapping from source child object to destination is including parent values
I'm currently experiencing an issue when trying to map the entire destination object from a child property on the source object.我目前在尝试从源 object 上的子属性 map 整个目标 object 时遇到问题。 Something similar as described here: Automapper - How to map from source child object to destination类似于此处所述的内容: Automapper - 如何从源子 object 到目标的 map
I've made use of the.ConstructUsing method as described in the link above however I'm seeing some weird behaviour where the outputted, mapped object is getting values from the parent instead of the child.我已经使用了上面链接中描述的 .ConstructUsing 方法,但是我看到一些奇怪的行为,其中输出的映射 object 从父级而不是子级获取值。
I made a demo of the problem here: https://dotnetfiddle.net/OdaGUr我在这里做了一个问题的演示: https://dotnetfiddle.net/OdaGUr
Is this a problem with my code, should I be using a different method to achieve what I'm trying to do or is this a fault with AutoMapper?这是我的代码的问题,我应该使用不同的方法来实现我想要做的事情还是 AutoMapper 的错误?
EDIT:编辑:
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;}
}
ConstructUsing()
is used to create the destination object, where the value should be stored in. In your case you are returning a Child2
object with the Id
value set to 2
(as returned by the ctx.Mapper.Map<Child1, Child2>(src.Child1)
line). ConstructUsing()
用于创建目标 object,该值应存储在其中。在您的情况下,您将返回一个Child2
object,其Id
值设置为2
(由ctx.Mapper.Map<Child1, Child2>(src.Child1)
返回ctx.Mapper.Map<Child1, Child2>(src.Child1)
行)。
However, after the object has been created, the default mapping will still be applied.但是,在创建 object 后,仍将应用默认映射。 This means that the Parent.Id
value will be saved in the Child2.Id
property, because the names of the property match ( "Id"
).这意味着Parent.Id
值将保存在Child2.Id
属性中,因为属性的名称匹配 ( "Id"
)。 So, the initial value of 2
will be replaced with the value 1
from the Parent
object.因此,初始值2
将替换为父Parent
中的值1
。
Depending on what you want to do, you might want to use ForMember()
to configure special handling on how the property values should be mapped.根据您想要执行的操作,您可能希望使用ForMember()
来配置有关如何映射属性值的特殊处理。 An example would be:一个例子是:
.ForMember(dest => dest.Id, src => src.MapFrom(it => it.Child1.Id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.