问题
I have a following class structure:
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
}
};
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
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?
回答1:
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
.
How do we work around this?
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());
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));
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.
来源:https://stackoverflow.com/questions/11346571/how-not-to-lose-properties-that-are-present-in-my-destination-object-but-are-not