gpt4 book ai didi

c# - AutoMapper 映射可为空的值类型

转载 作者:太空宇宙 更新时间:2023-11-03 16:19:04 25 4
gpt4 key购买 nike

AutoMapper 似乎不映射 null 可空值。它只会映射可空值的属性。

我如何告诉 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();
});

我错过了什么吗?

最佳答案

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

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 类型映射异常。

关于c# - AutoMapper 映射可为空的值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com