Nei*_*len 5 c# automapper automapper-4
我在解决如何获取Automapper 4.2.1以允许类型映射时遇到一些问题,其中目标值可能为空,具体取决于源值。
旧版本的 Automapper 允许通过 Mapper 配置设置AllowNullDestination标志,但我找不到新版本的等效配方,并且通过静态 Mapper 对象进行配置的旧机制似乎已过时。
我尝试了以下方法但没有成功:
这是一个演示该问题的简单测试用例。由于 Substitute 方法返回 null,因此在最后一行失败并出现 AutoMapperMappingException 。我希望这两个映射都能成功。
我宁愿避免在解决方案中使用.ForMember,因为在我试图解决的实际场景中,bool 和“object”(实际上是自定义类)之间的映射应该应用于整个对象树。
尽管 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<Source, Target>();
//How should the following mapping be modified to pass the test?
configuration.CreateMap<bool, object>()
.Substitute(i => i ? null : new object());
}).CreateMapper();
var target1 = mapper.Map<Source, Target>(new Source {Member = false}); //succeeds
Assert.IsNotNull(target1.Member); //pass
var target2 = mapper.Map<Source, Target>(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; }
}
}
Run Code Online (Sandbox Code Playgroud)
不要使用Substitute,而是使用ConvertUsing ...
configuration.CreateMap<bool, MyClass>()
.ConvertUsing(i => i ? null : new object());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4223 次 |
| 最近记录: |