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

use*_*229 4 c# enums boolean automapper

有人可以展示一个将bool属性映射到enum类型的示例吗?我担心null成员在destination。我需要有这样的东西:

null 属性值到第一个枚举值;

0 一秒钟;

1 到最后;

Luc*_*rsi 5

不幸的是,如此处所示AutoMapper null 源值和自定义类型转换器,无法映射?你不能直接将 "null" 映射到某个东西,因为 null 的映射总是返回 default(T),所以你不能做这样的事情:

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

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

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
}
Run Code Online (Sandbox Code Playgroud)