注: この質問は現在古くなっているため、古いバージョンの AutoMapper にのみ適用されます。ここで言及されているバグは修正されています。
問題:
Nullable<bool>
/を受け取り、bool?
を返すAutoMapper コンバーターがあります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)]
}
}
質問:
- これはバグですか、それとも仕様ですか?
- 設計によるものである場合、このように動作する理由は何ですか?
- 回避策をお勧めできますか?