我有以下示例对象..
public class ComplexObject
{
public string Name { get; set; }
public SimpleObject Child1 { get; set; }
public SimpleObject Child2 { get; set; }
}
public class SimpleObject : IEquatable< SimpleObject >
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int? Age { get; set; }
}
使用以下 AutoMapper 配置
Mapper.CreateMap<SimpleObject, SimpleObject>()
.ForAllMembers(expression=>expression.Condition(r=>!r.IsSourceValueNull));
Mapper.CreateMap<ComplexObject, ComplexObject>()
.ForAllMembers(expression=>expression.Condition(resolutionContext=>!resolutionContext.IsSourceValueNull));
以及以下 NUnit 测试...
[SetUp] public void Should_run_before_each_test()
{
child1 = new SimpleObject { FirstName = "Tom", LastName = "Smith", Age = 34, Gender = "Male" };
child2 = new SimpleObject { FirstName = "Andy", LastName = "Smith-bob", Age = 21, Gender = "Male" };
}
[ Test ]
public void Should_ignore_null_properties_in_nested_objects()
{
var source = new ComplexObject()
{
Name = "blue",
Child1 = new SimpleObject{FirstName = "dot", LastName = "net"}
};
var destination = new ComplexObject()
{
Name = "Andy",
Child1 = child1,
Child2 = child2
};
destination = Mapper.Map(source, destination);
destination.Name.Should(Be.EqualTo(source.Name));
destination.Child1.FirstName.Should(Be.EqualTo("dot"));
destination.Child1.LastName.Should(Be.EqualTo("net") );
destination.Child1.Age.Should(Be.EqualTo(child1.Age) );
destination.Child1.Gender.Should(Be.EqualTo(child1.Gender) );
}
上面的测试在断言年龄时失败,因为 AutoMapper 正在将 null 推送到目标对象。
我是否对 AutoMapper 期望过高,或者我错过了一些重要的地图配置步骤。
最终目标是通过 MVC 操作将一个非常复杂的域对象绑定到传入的表单数据。然后,AutoMapper 将用于仅将非空属性(在对象图的所有深度)合并到整个多步骤表单中维护的真实实例中。
以防万一有人需要知道...我还尝试了以下映射配置,但没有任何运气:(
Mapper.CreateMap<ComplexObject, ComplexObject>()
.ForMember(x=>x.Child1, l=>l.ResolveUsing(x=>x.Child1 == null?null:Mapper.Map<SimpleObject,SimpleObject>(x.Child1)))
.ForMember(x=>x.Child2, l=>l.ResolveUsing(x=>x.Child2 == null?null:Mapper.Map<SimpleObject,SimpleObject>(x.Child2)))
.ForAllMembers(expression=>expression.Condition(resolutionContext=>!resolutionContext.IsSourceValueNull));