Problem:
I have an AutoMapper converter that takes a Nullable<bool>
/bool?
and returns a string
. I apply this globally to my profile, and it works for true
and false
but not for null
.
Here is what I have in my AutoMapper profile:
CreateMap<bool?, string>()
.ConvertUsing<NullableBoolToLabel>();
And here is the converter class:
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)";
}
}
Example that demonstrates problem
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)]
}
}
Questions:
- Is this a bug or by design?
- If it's by design, what is the reasoning behind it working this way?
- Can you recommend a workaround?