I am trying to figure out how to merge two complex object instances using AutoMapper. The parent object has a property which is a collection of child objects:
public class Parent
{
public List<Child> Children { get; set; }
}
public class Child
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
I have two instances of Parent
:
var parentOne = new Parent()
{
Children = new List<Child>() { new Child() { A = "A", B = "B", C = "C" } }
};
var parentTwo = new Parent()
{
Children = new List<Child>() { new Child() { C = "Updated value" } }
};
I would like to be able to merge values from parentOne
to parentTwo
, without overwriting the value of C
in parentTwo
. The maps I have created are as follows:
Mapper.CreateMap<Parent, Parent>()
.ForMember(parent => parent.Children, opt => opt.UseDestinationValue());
Mapper.CreateMap<Child, Child>()
.ForMember(child => child.C, opt => opt.Ignore());
Mapper.Map(parentOne, parentTwo);
As I understand it, AutoMapper will create new instances of complex properties unless you use the UseDestinationValue()
option. However, after executing the code above, parentTwo.C
equals "C"
instead of "Updated value"
.
It looks to me like it's keeping the instance of List<Child>
, but it is creating new instances of Child
within the List. Unfortunately, I'm struggling to come up with a map that will keep each instance of Child
as well.
Any help would be much appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…