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

标签 c# enums boolean automapper

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

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

0 到一秒;

1 到最后;

最佳答案

不幸的是,如这里所表达的AutoMapper null source value and custom type converter, fails to map?你不能直接将“null”映射到某个东西,因为 null 的映射将始终返回 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
}

关于c# - 如何正确使用 automapper 将 bool 映射到枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029096/

相关文章:

c# - 配置。保存在网络驱动器上

Java:Spring RestControllerAdvice 异常处理程序中未触发自定义枚举 validator 注释

SPARQL 中的 boolean 检查,检查语句是否存在

C++ - || 如何运算符(operator)工作?

MySQL boolean 搜索 - 如何过滤掉所有不包含至少 2 个输入字符串的结果?

c# - 在csharp中将扩展字符转换为int

c# - 如何在新的 ASP.NET Core 中调用 Web API 非默认构造函数

c# - 学习 Objective C 时需要了解的关键事项?

postgresql - 当 TEXT 值不匹配时,postgres 将文本转换为 ENUM

java - 使用枚举的序数是一种好习惯吗?