如何不丢失是present我的目标对象,但不是在我的源对象使用AutoMapper映射后的属性 [英] How not to lose properties that are present in my destination object but are NOT in my source object after mapping using AutoMapper
问题描述
我有下面的类结构:
public class A
{
public bool Property1 { get; set; }
public bool Property2 { get; set; }
}
public class ContainerForA
{
public A A { get; set; }
}
public class A1
{
public bool Property1 { get; set; }
}
public class ContainerForA1
{
public A1 A { get; set; }
}
我创建此组类的映射:
I create a mapping for this set of classes:
Mapper.CreateMap<A1, A>();
Mapper.CreateMap<ContainerForA1, ContainerForA>();
我创建这个组类的一个实例:
I create an instance of this set of classes:
var cnt_a = new ContainerForA()
{
A = new A()
{
Property1 = false,
Property2 = true
}
};
var cnt_a1 = new ContainerForA1()
{
A = new A1()
{
Property1 = true
}
};
如果我称之为 Mapper.Map(cnt_a1.A,cnt_a.A)
我得到的结果我期待:这两个属性( Property1
和 Property2
对象)的 cnt_a 是真正
If I call Mapper.Map(cnt_a1.A, cnt_a.A)
I'm getting the result I was expecting: both properties (Property1
and Property2
) of object cnt_a are true
但是,如果我称之为 Mapper.Map(cnt_a1,cnt_a)
我收到如此 Property1
和假为 Property2
。有人能解释我为什么?而没有任何选项,我宣布我的映射的方式,所以我不会失去的是present我的目标对象,但不是在我的源对象?属性
But if I call Mapper.Map(cnt_a1, cnt_a)
I'm getting true for Property1
and false for Property2
. Could someone explain me why? And is there any option for me to declare my mappings in the way so I won't lose properties that are present in my destination object but are NOT in my source object?
推荐答案
我猜想,当你从 ContainerForA1
映射到 ContainerForA
,当映射属性的,它 ContainerForA
A 一个新实例>,而不是用现有之一。这将使用默认值,所有属性,这是假
为布尔
。
I would guess that when you map from ContainerForA1
to ContainerForA
, that when mapping the property A, it creates a new instance of A
for ContainerForA
rather than using the existing one. This will use the default values for all of the properties, which is false
for a bool
.
我们如何解决此问题?
首先,我们需要告诉AutoMapper不覆盖的属性的上ContainerForA。为了做到这一点,我们会告诉AutoMapper忽略属性。
First, we need to tell AutoMapper to not overwrite the property A on ContainerForA. To do that, we will tell AutoMapper to ignore the property.
Mapper.CreateMap<ContainerForA1, ContainerForA>()
.ForMember(cForA => cForA.A, option => option.Ignore());
现在,我们需要手动更新,使用AfterMap
Now we need to update A manually, using AfterMap
Mapper.CreateMap<ContainerForA1, ContainerForA>()
.ForMember(cForA => cForA.A, option => option.Ignore())
.AfterMap((cForA1, cForA) => Mapper.Map(cForA1.A, cForA.A));
您可能会想一些检查,添加到AfterMap方法,以确保cForA.A不为空。我会留给你。
You will probably want to add some checks to the AfterMap method to ensure that cForA.A is not null. I'll leave that for you.
这篇关于如何不丢失是present我的目标对象,但不是在我的源对象使用AutoMapper映射后的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!