gpt4 book ai didi

c# - 如果 Not Null,则 AutoMapper 映射嵌套对象的属性

转载 作者:行者123 更新时间:2023-11-30 17:59:03 32 4
gpt4 key购买 nike

我有以下示例对象..

  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 期望过高,还是错过了一些重要的 map 配置步骤。

最终目标是通过 MVC 操作将非常复杂的域对象绑定(bind)到传入的表单数据。然后,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));

最佳答案

如果源值为空,为什么你期望目标对象的值不为空? int? 的默认值为 null,因此,当您调用

destination.Child1.Age.Should(Be.EqualTo(child1.Age));

.Should 失败了。这应该是预期的行为。

尝试类似 Assert.Null(detination.Child1.Age) 的操作,它应该会通过。 AutoMapper 不会“推送”值,没有源值,因此,Age 只会使用默认值。

关于c# - 如果 Not Null,则 AutoMapper 映射嵌套对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11580938/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com