1

我正在尝试在不使用泛型的情况下配置 AutoMapper,因为我想在运行时配置它。

我想配置 SubstiteNulls 方法并能够执行以下操作:

Mapper.CreateMap<Source, Dest>()
    .ForMember(dest => dest.Value, opt => opt.NullSubstitute("Other Value"));

但我无法弄清楚如何做到这一点。您可以将它们的 Type 对象传递给CreateMap工厂方法,但是当您使用该ForMember方法时,该opt对象不包含该NullSubstitute方法,我想这是由于我在这里使用的缺少泛型。

关于如何实现这一目标的任何想法?

更新

这些是我得到的选项:

在此处输入图像描述

4

1 回答 1

3

Currently the NullSubstitute configuration is not available on the IMappingExpression interface which is used when you are using the non generic version of CreateMap.

There is no limitation which is preventing Automapper to have this method on the IMappingExpression so currently this is just not supported.

You have three options:

  • Create an issue on Github and wait until it is implemented
  • Fork the project and implement the method yourself. It is very easy you can use the generic version as an example.
  • Or if you want a quick but very dirty solution. With reflection you can get the underlaying PropertyMap from the configuration and call the SetNullSubstitute method on it:

    Mapper.CreateMap(typeof(Source), typeof(Dest))
        .ForMember("Value", opt =>
            {
                FieldInfo fieldInfo = opt.GetType().GetField("_propertyMap",
                    BindingFlags.Instance | BindingFlags.NonPublic);
                var propertyMap = (PropertyMap) fieldInfo.GetValue(opt);
                propertyMap.SetNullSubstitute("Null Value");
        });
    
于 2013-09-02T15:39:11.650 回答