繁体   English   中英

AutoMapper空源值和自定义类型转换器,无法映射?

[英]AutoMapper null source value and custom type converter, fails to map?

当使用带有AutoMapper的自定义类型转换器(ITypeConverter)时,如果源值为null ,则似乎没有输入类型转换器代码,例如:

Mapper.CreateMap<string, Enum>().ConvertUsing<EnumConverter>();

Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>("StringValue1"));
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>(null);
Assert.AreEqual(Enum.Value1, Mapper.Map<Enum?>(null);

类型转换器看起来像:

public class EnumConvertor: ITypeConverter<string, Enum>
{
    public Enum Convert(ResolutionContext context)
    {
        string value = (string) context.SourceValue;

        switch (value)
        {
            case "StringValue2":
                return Enum.Value2;
            case "StringValue3":
                return Enum.Value3;
            case "StringValue1":
            default:
                return Enum.Value1;
        }
    }
}

在最后两种情况下,结果是:

Assert.AreEqual(Enum.Value1, Mapper.Map<Enum>(null);

0-无效的枚举值

Assert.AreEqual(Enum.Value1, Mapper.Map<Enum?>(null);

空值

从调试到测试,在这两种情况下,自定义TypeConverter永远不会被击中,并且似乎AutoMapper在映射器中具有一些初始检查以映射而不使用TypeConverter?

如果我指定一个空字符串(“”),则测试将按预期工作。

快速查看一下automapper的源代码,Mapper.Map(对象源)执行空检查。 如果source为null,它将返回T的默认值:

    public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
    {
        var mappedObject = default(TDestination);
        if (source != null)
        {
            var sourceType = source.GetType();
            var destinationType = typeof(TDestination);

            mappedObject = (TDestination)Map(source, sourceType, destinationType, opts);
        }
        return mappedObject;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM