我想将 POCO 映射到一个并且AutomapperImmutableDictionary<string, object>
引发异常,因为.Add
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