尝试使用自动映射器映射不可变字典时出错



我想将 POCO 映射到ImmutableDictionary<string, object>并且自动映射器引发异常,因为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(...)));

相关内容

  • 没有找到相关文章

最新更新