2016-03-16 83 views

回答

2

Unfortutely,因为这里表达AutoMapper null source value and custom type converter, fails to map?你不能“空”直接映射到东西,因为地图空的将始终返回默认值(T),所以你不能做这样的事情:

CreateMap<bool?, MyStrangeEnum>() 
     .ConvertUsing(boolValue => boolValue == null 
      ? MyStrangeEnum.NullValue 
      : boolValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False); 

如果映射对象属性,另一方面,它将工作:

public class MapperConfig : Profile 
{ 
    protected override void Configure() 
    { 
     CreateMap<Foo, Bar>() 
      .ForMember(dest => dest.TestValue, 
       e => e.MapFrom(source => 
        source.TestValue == null 
         ? MyStrangeEnum.NullValue 
         : source.TestValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False)); 
    } 
} 

public class Foo 
{ 
    public Foo() 
    { 
     TestValue = true; 
    } 
    public bool? TestValue { get; set; } 
} 

public class Bar 
{ 
    public MyStrangeEnum TestValue { get; set; } 
} 

public enum MyStrangeEnum 
{ 
    NullValue = -1, 
    False = 0, 
    True = 1 
} 
+0

很好的解决方案,谢谢! – user3818229

0

尝试像下面的代码:

枚举:

public enum BoolVal { 
    NullVal = -1 , 
    FalseVal = 0 , 
    TrueVal = 1 
} 

申报价值:

 var val = BoolVal.NullVal; // OR (BoolVal.FalseVal ,BoolVal.TrueVal) 

测试值:

// This will return => null or true or false 
bool? value1 = (val == BoolVal.NullVal ? null : (bool?)Convert.ToBoolean(val));