2016-06-14 38 views
0

我想將POCO映射到ImmutableDictionary<string, object>,並且由於ImmutableDictionary中不支持Add操作,所以Automapper引發異常。嘗試使用AutoMapper映射ImmutableDictionary時出錯

POCO對象位於源類型中名爲Data的屬性中,該屬性映射到目標中的DataBag屬性。目前還不知道Data的類型。

我使用這個映射:

var t = new MapperConfiguration(cfg => 
        cfg.CreateMap(@event.GetType(), typeof(StoredEvent)) 
         .ForMember("DataBag", opt => opt.MapFrom("Data"))); 

,並收到此錯誤:

Mapping types: 
Dictionary`2 -> ImmutableDictionary`2 
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] -> System.Collections.Immutable.ImmutableDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 

Destination path: 
StoredEvent.DataBag.DataBag.DataBag 

爲了解決這個我試過用自定義解析:

public class ImmutableDictionaryResolver : IValueResolver 
{ 
    public ResolutionResult Resolve(ResolutionResult source) 
    { 
     var dictionary = Mapper.Map<Dictionary<string, object>>(source.Value); 
     return source.New(dictionary.ToImmutableDictionary()); 
    } 
} 

有了這個映射:

var t = new MapperConfiguration(cfg => 
      cfg.CreateMap(@event.GetType(), typeof(StoredEvent)) 
      .ForMember(nameof(StoredEvent.DataBag), opt => 
       opt.ResolveUsing<ImmutableDictionaryResolver>().FromMember("Data"))); 

但我仍然收到相同的錯誤。在第二種情況下,它的投訴與此:

Mapping types: 
ImmutableDictionary`2 -> ImmutableDictionary`2 
System.Collections.Immutable.ImmutableDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] -> System.Collections.Immutable.ImmutableDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 

Destination path: 
StoredEvent.DataBag.DataBag 

回答

0

而不是使用ForMember的嘗試使用ConstructUsing所以你可以給它一個你不可變對象的值。

var t = new MapperConfiguration(cfg => 
      cfg.CreateMap(@event.GetType(), typeof(StoredEvent)) 
      .ConstructUsing(x => new ImmutableDictionaryResolver(...)));