问题
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