简体   繁体   English

如何正确使用automapper将bool映射到枚举?

[英]How to map bool to a enum using automapper properly?

Could someone show an example with mapping bool property to a enum type? 有人可以展示一个将bool属性映射到enum类型的示例吗? I'm worry about null members in destenition. 我担心null成员。 I need to have something like these: 我需要这样的东西:

null property value to a first enum value; null属性值为第一个枚举值;

0 to a second; 0到1秒;

1 to the last; 1到最后;

Unfortutely, as expressed here AutoMapper null source value and custom type converter, fails to map? 不幸的是,如此处所表示的AutoMapper null源值和自定义类型转换器,无法映射? you can't directly map "null" to something, because a map of null will always return default(T), so you can't do something like this: 你不能直接将“null”映射到某个东西,因为null的映射将始终返回默认值(T),所以你不能做这样的事情:

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

If you map an object property, on the other hand, it will work: 另一方面,如果映射对象属性,它将起作用:

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
}

try like the below code : 尝试类似下面的代码:

Enum : 枚举:

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

Declare Value : 声明价值:

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

Test Value : 测试值:

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

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

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