[英]Error trying to map ImmutableDictionary with AutoMapper
我想將POCO映射到ImmutableDictionary<string, object>
並且Automapper引發異常,因為ImmutableDictionary
不支持Add
操作。
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
不要使用ForMember
而是嘗試使用ConstructUsing
以便為您的不可變對象提供一個值。
var t = new MapperConfiguration(cfg =>
cfg.CreateMap(@event.GetType(), typeof(StoredEvent))
.ConstructUsing(x => new ImmutableDictionaryResolver(...)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.