使用 AutoMapper:映射嵌套集合时,我希望任何未映射的属性都保留其原始值。相反,它们被设置为空。
示例:
我有这四个类
(注意Test2Child
有Name
属性,而Test1Child
没有):
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; }
}
...和一个简单的映射设置。
Mapper.CreateMap<Test1, Test2>();
Mapper.CreateMap<Test1Child, Test2Child>().ForMember(m => m.Name, o => o.Ignore());
Mapper.AssertConfigurationIsValid(); // Ok
我希望在映射期间保留 的原始值Test2Child.Name
...。我希望这是任何未映射属性的默认行为。
Test1Child
当我直接从to映射时Test2Child
,它工作正常;Value
被映射并被Name
保留:
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
当映射用于嵌套集合(List<Test1Child>
to List<Test2Child>
)时,
Value
映射正确......但原始值Name
丢失了!
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.
我该如何解决?