从DB查询数据中获取枚举描述

问题描述 投票:-1回答:1

我从DB中获取数据,并将其填充到一个模型中,然后返回该模型.我的枚举类。

  public enum ProcessEnum
{
    [Description("Done")]
    Done = 1,
    [Description("In Progress")]
    InProgress = 2,
    [Description("Pending")]
    Pending = 3,
}

响应模型类:

     public class ReportsFilterModel
    {
        [Required]
        public ProcessEnum processStatus { get; set; }
    }

方法类。

 finalReports = await report
                    .Select(x => new ReportsFilterModel
                    {
                        Id = x.Id,
                        processStatus = (ProcessEnum)x.ProcessID
                    }).ToListAsync();

这将给我返回InProgess,我需要描述,即 "In Progress".This is just a snippet wheres there are a lot places I need the description of the enum.

c# asp.net-core asp.net-web-api enums dbcontext
1个回答
0
投票

你可以使用 Display 属性。

public enum MyColors
{
    [Display(Name = "Rot")] Red,
    [Display(Name = "Grün")] Green,
    [Display(Name = "Blau")] Blue
}

public enum MyAnimals
{
    Horse,
    Dog,
    Cat
}

public void DoThings()
{
    var enumList = new List<Enum>
    {
        MyColors.Red,
        MyColors.Green,
        MyColors.Blue,
        MyAnimals.Horse,
        MyAnimals.Dog,
        MyAnimals.Cat,
    };

    enumList.ForEach(e => Console.WriteLine(e.GetName()));
    Console.WriteLine("-------------------------------");
    // print 'Display Name' if it exists, else print it's name as is.
    enumList.ForEach(e => Console.WriteLine(e.GetAttribute<DisplayAttribute>()?.Name ?? "-"));
    Console.WriteLine("-------------------------------");
    enumList.ForEach(e => Console.WriteLine(e.GetDisplayName()));
}

输出。

Red
Green
Blue
Horse
Dog
Cat
-------------------------------
Rot
Grün
Blau
-
-
-
-------------------------------
Rot
Grün
Blau

编辑:刚刚意识到,我在我的fiddle项目中使用了一个记录器服务类。将其替换为 Console.WriteLine.

© www.soinside.com 2019 - 2024. All rights reserved.