2

AutoMapper 似乎没有映射可空值。如果可以为空值,它只会映射属性。

如何告诉 AutoMapper 始终将空值(任何类型)从源映射到目标?

编辑:

https://github.com/AutoMapper/AutoMapper/blob/master/src/AutoMapper/Mappers/MapperRegistry.cs

AssignableMapper 在 NullableMapper 之前,如果源为空,则可防止映射可空类型。

我在开头添加了这段代码以插入 NullableMapper。

container.RegisterSingle(() =>
            {
                // we need to add a nullable mapper to ensure Nullable<value> gets mapped correctly
                var mappers = AutoMapper.Mappers.MapperRegistry.AllMappers().ToList();
                mappers.Insert(0, new AutoMapper.Mappers.NullableMapper());
                return mappers.AsEnumerable();
            });

我错过了什么吗?

4

1 回答 1

0

我相信这不能那么容易配置。我试过这个:

var r = (IObjectMapper[])typeof(MappingEngine).GetField("_mappers", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(((MappingEngine)(AutoMapper.Mapper.Engine)));

Array.Resize(ref r, r.Length + 1);
Array.Copy(r, 0, r, 1, r.Length - 1);
r[0] = new NullableMapper();

typeof(MappingEngine).GetField("_mappers", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(((MappingEngine)(AutoMapper.Mapper.Engine)), r);

甚至这样:

MapperRegistry.AllMappers = () => new IObjectMapper[]
{
    new NullableMapper(),
    new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers()),
    new StringMapper(),
    new FlagsEnumMapper(),
    new AssignableMapper(),
    new EnumMapper(),
    new PrimitiveArrayMapper(),
    new ArrayMapper(),
    new EnumerableToDictionaryMapper(),
    new DictionaryMapper(),
    new ReadOnlyCollectionMapper(),
    new CollectionMapper(),
    new EnumerableMapper(),
    new NullableSourceMapper(),
    new ImplicitConversionOperatorMapper(),
    new ExplicitConversionOperatorMapper(),
};

这对我没有帮助。当它应该将 null 映射到属性时,它仍然会抛出错误的 null 类型映射异常。

于 2013-11-06T11:22:09.337 回答