注意:这个问题现在已经过时了,只适用于旧版本的 AutoMapper。此处提到的错误已得到修复。
问题:
我有一个 AutoMapper 转换器,它接受一个Nullable<bool>
/bool?
并返回一个string
. 我将此全局应用于我的个人资料,它适用于true
但false
不适用于null
.
这是我的 AutoMapper 配置文件中的内容:
CreateMap<bool?, string>()
.ConvertUsing<NullableBoolToLabel>();
这是转换器类:
public class NullableBoolToLabel : ITypeConverter<bool?, string>
{
public string Convert(bool? source)
{
if (source.HasValue)
{
if (source.Value)
return "Yes";
else
return "No";
}
else
return "(n/a)";
}
}
演示问题的示例
public class Foo
{
public bool? IsFooBarred { get; set; }
}
public class FooViewModel
{
public string IsFooBarred { get; set; }
}
public class TryIt
{
public TryIt()
{
Mapper.CreateMap<bool?, string>().ConvertUsing<NullableBoolToLabel>();
Mapper.CreateMap<Foo, FooViewModel>();
// true (succeeds)
var foo1 = new Foo { IsFooBarred = true };
var fooViewModel1 = Mapper.Map<Foo, FooViewModel>(foo1);
Debug.Print("[{0}]", fooViewModel1.IsFooBarred); // prints: [Yes]
// false (succeeds)
var foo2 = new Foo { IsFooBarred = false };
var fooViewModel2 = Mapper.Map<Foo, FooViewModel>(foo2);
Debug.Print("[{0}]", fooViewModel2.IsFooBarred); // prints: [No]
// null (fails)
var foo3 = new Foo { IsFooBarred = null };
var fooViewModel3 = Mapper.Map<Foo, FooViewModel>(foo3);
Debug.Print("[{0}]", fooViewModel3.IsFooBarred); // prints: []
// should print: [(n/a)]
}
}
问题:
- 这是一个错误还是设计使然?
- 如果是设计使然,那么以这种方式工作的原因是什么?
- 你能推荐一个解决方法吗?