将不可读的DB数据显示为可读格式

时间:2019-04-09 23:56:30

标签: c# asp.net-core-2.0 class-properties

我有一个表,其中包含仅包含数字的字段。我想要实现的是在枚举中表示实际数字,并将数字“转换”为可读的值。

例如,我有一个User表,其中包含一个名为User Roles的字段。角色共有4种:super adminadminmanagerregular user

Super Admin is represented as 0 Admin is represented as 1 Manager is represented as 2 ManagerAdmin is represented by 3 (combination of admin = 1 and Manager = 2) Regular user is represented as 4

当尝试从Enum = 3进行翻译时,如何显示Manager; Admin

  

UserModel

public int UserRoles {get; set;} public string UserNames {get; set;} public string UserAddress {get; set;}

  

枚举

public enum UserRole
{
  SuperAdmin = 0,
  Admin = 1,
  Manager = 2,
  Regular = 3
  ManagerAdmin = 4
}
  

C#代码

public IEnumerable<User> UserInfo()
{
 var userInfo = context.User.Select(u => new UserModel
 {
   UserRoles = u.Roles, //this is where I want the actual string roles
   UserNames = u.Names,
   UserAddress = u.Address
 }).ToList();
}
  
    

//我在想这样的事情:

  
if(u.Roles == 0)
{
    // project Super Admin
}
else if(u.Roles == 1)
{
    // project Admin
} etc...

1 个答案:

答案 0 :(得分:1)

Enum.GetName(typeof(UserRole), enumValue)会给您所需的Rolename。这里enumValue将为0、1、2、3

var userInfo = context.User.Select(u => new UserModel
{
   UserRoles =Enum.GetName(typeof(UserRole), u.Roles) , 
   UserNames = u.Names,
   UserAddress = u.Address
}).ToList();