2014-03-13 46 views
3

當使用自定義類型轉換(ITypeConverter)與AutoMapper它似乎並沒有進入類型轉換器代碼,如果源值爲null,如:AutoMapper空值來源和自定義類型轉換器,無法映射?

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); 

的類型轉換器看起來像:

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; 
     } 
    } 
} 

在後兩種情況下,結果是:

Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>(null); 

0 - 不是有效的枚舉值

Assert.AreEqual(Enum.Value1, Mapper.Map<Enum?>(null); 

從調試到測試,在這兩種情況下的定義TypeConverter從來沒有被擊中,似乎AutoMapper在映射器映射而不訴諸TypeConverter的一些初步的檢查?

如果我指定一個空字符串(「」),測試按預期工作。

回答

11

快速瀏覽一下automapper的源代碼,Mapper.Map(object source)做了一個空的檢查。如果source爲null,它將返回默認值T:

public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts) 
    { 
     var mappedObject = default(TDestination); 
     if (source != null) 
     { 
      var sourceType = source.GetType(); 
      var destinationType = typeof(TDestination); 

      mappedObject = (TDestination)Map(source, sourceType, destinationType, opts); 
     } 
     return mappedObject; 
    } 
+3

我也注意到了這一點。 'TSource'和'TDestination'的重載沒有這些檢查,大概是因爲已知類型檢索該類型的任何映射,如果源對象爲'null'則無法確定。它確實有道理,但有點不確定。因此正確的測試應該是'Assert.AreEqual(Enum.Value1,Mapper.Map (null);'解決了這個問題。 – Mig

相關問題