When using a custom type converter (ITypeConverter) with AutoMapper it does not seem to enter the type converters code if the source value is null
, e.g:
Mapper.CreateMap<string, Enum>().ConvertUsing<EnumConverter>();
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>("StringValue1"));
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>(null);
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum?>(null);
The type converter looks something like:
public class EnumConvertor: ITypeConverter<string, Enum>
{
public Enum Convert(ResolutionContext context)
{
string value = (string) context.SourceValue;
switch (value)
{
case "StringValue2":
return Enum.Value2;
case "StringValue3":
return Enum.Value3;
case "StringValue1":
default:
return Enum.Value1;
}
}
}
In the last two cases, the results are:
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>(null);
0 - Not a valid enum value
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum?>(null);
Null
From debugging into the tests, in these two cases the custom TypeConverter never gets hit and it seems AutoMapper has some initial checks in the mapper to map without resorting to the TypeConverter?
If I specify an empty string ("") the test works as expected.