views:

199

answers:

1

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:

  1. Is this a bug or by design?
  2. If it's by design, what is the reasoning behind it working this way?
  3. Can you recommend a workaround?
A: 

Do you need to specify a ConvertUsing for the Map? Otherwise, I'm not sure how it would know how to use the IsFooBarred member of the Foo class. But I'm not familar with the Mapper, and perhaps it can figure this out (it does seem to in the first two cases).

If you put a breakpoint in Convert does it get hit (in the debugger) in any of the 3 cases?

Andy Jacobs