AutoMapper TypeConverter mapping nullable type to not-nullable type

房东的猫 提交于 2019-12-31 03:38:06

问题


I'm using AutoMapper, and I've registered a TypeConverter to map nullable long values to long values like so:

public class NullableLongToLongConverter : TypeConverter<long?, long>
{
    protected override long ConvertCore(long? source)
    {
        return source ?? 0;
    }
}

This works fine, and automatically picks up any nullable longs being converted to longs.

However, I've got some other maps which want to 'convert' nullable longs to nullable longs. These also end up using this type converter. For example, both properties are getting set to 0 in the code below, but I'd expect NullableLong to be set to null. Am I doing something wrong?

public class Foo
{
    public long? NullableLong{get {return null;}}
    ......
}

public class Bar
{
    public long NotNullableLong{get;set;}
    public long? NullableLong{get;set;}
    ......
}

public static class ComplicatedMapRegister
{
    public static void RegisterMap()
    {
        Mapper.CreateMap<Foo, Bar>()
            .ForMember(b => b.NotNullableLong, opt => opt.MapFrom(f.NullableLong))
            .ForMember(b => b.NullableLong, opt => opt.MapFrom(f.NullableLong))
            .....
    }
}

public static class AutoMapperRegistration
{
    public static void RegisterAllMaps()
    {
        Mapper.CreateMap<long?, long>().ConvertUsing<NullableLongToLongConverter>();
        ComplicatedMapRegister.RegisterMap();
    }
}

回答1:


You've only registered a converter that maps from long? to long. Don't you just need to create and register a 'converter' that will map from long? to long??



来源:https://stackoverflow.com/questions/8806771/automapper-typeconverter-mapping-nullable-type-to-not-nullable-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!