如何正确使用 automapper 将 bool 映射到枚举?
How to map bool to a enum using automapper properly?
有人可以展示一个将 bool
属性 映射到 enum
类型的示例吗?我担心 null
成员的死亡。
我需要这样的东西:
null
属性 值到第一个枚举值;
0
秒;
1
到最后;
试试下面的代码:
枚举:
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));
不幸的是,如此处所述AutoMapper null source value and custom type converter, fails to map?,您不能直接将 "null" 映射到某物,因为 null 的映射将始终是 return default(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
}
有人可以展示一个将 bool
属性 映射到 enum
类型的示例吗?我担心 null
成员的死亡。
我需要这样的东西:
null
属性 值到第一个枚举值;
0
秒;
1
到最后;
试试下面的代码:
枚举:
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));
不幸的是,如此处所述AutoMapper null source value and custom type converter, fails to map?,您不能直接将 "null" 映射到某物,因为 null 的映射将始终是 return default(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
}