Using AutoMapper: When mapping nested collections, I expect any unmapped properties to have their original values retained. Instead, they are being set to null.
Example:
I have these four classes
(note that Test2Child
has the Name
property, while Test1Child
does not):
public class Test1
{
public List<Test1Child> Children { get; set; }
}
public class Test2
{
public List<Test2Child> Children { get; set; }
}
public class Test1Child
{
public int Value { get; set; }
}
public class Test2Child
{
public string Name { get; set; }
public int Value { get; set; }
}
...and a simple mapping setup.
Mapper.CreateMap<Test1, Test2>();
Mapper.CreateMap<Test1Child, Test2Child>().ForMember(m => m.Name, o => o.Ignore());
Mapper.AssertConfigurationIsValid(); // Ok
I want the original value of Test2Child.Name
to be retained during mapping.... I expect this to be the default behaviour for any unmapped properties.
When I map directly from Test1Child
to Test2Child
, it works fine; Value
is mapped and Name
is retained:
var a = new Test1Child {Value = 123};
var b = new Test2Child {Name = "fred", Value = 456};
Mapper.Map(a, b);
Assert.AreEqual(b.Value, 123); // Ok
Assert.AreEqual(b.Name, "fred"); // Ok
When the mapping is for a nested collection (List<Test1Child>
to List<Test2Child>
),
Value
is mapped correctly... but the original value for Name
is lost!
var c = new Test1 { Children = new List<Test1Child> { new Test1Child { Value = 123 } } };
var d = new Test2 { Children = new List<Test2Child> { new Test2Child { Name = "fred", Value = 456 } } };
Mapper.Map(c, d);
Assert.AreEqual(d.Children[0].Value, 123); // Ok
Assert.AreEqual(d.Children[0].Name, "fred"); // FAILS! Name is null.
How do I fix this?