java允许值为空_如何配置Automapper 4以允许空目标值

我在解决如何获得 Automapper 4.2.1 以允许类型映射时遇到一些问题,其中目标值可能为null,具体取决于源值 .

较旧版本的Automapper允许通过Mapper配置设置 AllowNullDestination 标志,但我找不到新版本的等效配方,并且通过静态Mapper对象配置的旧机制似乎已经过时 .

我试过以下但没有成功:

Mapper.Configuration.AllowNullDestinationValues = true;

Mapper.AllowNullDestinationValues = true;

Mapper.Initialize(c => c.AllowNullDestinationValues = true);

这是一个简单的测试案例,展示了这个问题 . 由于Substitute方法返回null,因此在 AutoMapperMappingException 的最后一行失败 . 我希望两个映射都能成功 .

我宁愿避免在解决方案中使用 .ForMember 因为在真实场景中我应该在整个对象树中应用对象'(实际上是一个自定义类) .

虽然StackOverflow上有几个类似的问题,但我还没有找到一个引用最新版Automapper的问题 .

在此先感谢您的任何建议

using AutoMapper;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AutoMapperTest

{

[TestClass]

public class ExampleTest

{

[TestMethod]

public void NullDestinationCanBeMapped()

{

var mapper = new MapperConfiguration(configuration =>

{

configuration.CreateMap();

//How should the following mapping be modified to pass the test?

configuration.CreateMap()

.Substitute(i => i ? null : new object());

}).CreateMapper();

var target1 = mapper.Map(new Source {Member = false}); //succeeds

Assert.IsNotNull(target1.Member); //pass

var target2 = mapper.Map(new Source {Member = true}); //fails to map with exception

Assert.IsNull(target2.Member); //not reached

}

}

public class Source

{

public bool Member { get; set; }

}

public class Target

{

public object Member { get; set; }

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值