2013-01-31 266 views
2

AutoMapper似乎沒有映射null爲null的值。它只會映射屬性,如果可爲空的值。AutoMapper映射空值類型

如何讓AutoMapper始終將來自源的空值(任何類型)映射到目標?

編輯:

https://github.com/AutoMapper/AutoMapper/blob/master/src/AutoMapper/Mappers/MapperRegistry.cs

的AssignableMapper是防止空類型從得到映射如果源是空的NullableMapper之前。

我添加了這段代碼在最開始插入NullableMapper。

container.RegisterSingle(() => 
      { 
       // we need to add a nullable mapper to ensure Nullable<value> gets mapped correctly 
       var mappers = AutoMapper.Mappers.MapperRegistry.AllMappers().ToList(); 
       mappers.Insert(0, new AutoMapper.Mappers.NullableMapper()); 
       return mappers.AsEnumerable(); 
      }); 

我錯過了什麼嗎?

+0

你使用的是什麼版本? –

+0

我使用的是2.2版本 –

+0

您可以查看NuGet上的最新預發佈版本嗎? –

回答

0

我相信這不能這麼容易配置。我曾經嘗試這樣做:

var r = (IObjectMapper[])typeof(MappingEngine).GetField("_mappers", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(((MappingEngine)(AutoMapper.Mapper.Engine))); 

Array.Resize(ref r, r.Length + 1); 
Array.Copy(r, 0, r, 1, r.Length - 1); 
r[0] = new NullableMapper(); 

typeof(MappingEngine).GetField("_mappers", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(((MappingEngine)(AutoMapper.Mapper.Engine)), r); 

即使這樣:

MapperRegistry.AllMappers =() => new IObjectMapper[] 
{ 
    new NullableMapper(), 
    new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers()), 
    new StringMapper(), 
    new FlagsEnumMapper(), 
    new AssignableMapper(), 
    new EnumMapper(), 
    new PrimitiveArrayMapper(), 
    new ArrayMapper(), 
    new EnumerableToDictionaryMapper(), 
    new DictionaryMapper(), 
    new ReadOnlyCollectionMapper(), 
    new CollectionMapper(), 
    new EnumerableMapper(), 
    new NullableSourceMapper(), 
    new ImplicitConversionOperatorMapper(), 
    new ExplicitConversionOperatorMapper(), 
}; 

與本次非幫我。當它只是將null映射到屬性時,它仍會拋出錯誤的空類型映射的異常。