Search code examples
c#asp.net-core-2.0class-properties

Displaying non readable DB data into readable format


I have a table that contains a field that only has numbers. What I'm trying to achieve is to represent the actual numbers within an enum and "translate" the numbers into values that is readable.

For example, I have a User table with a field called User Roles. There are 4 kinds of roles: super admin, admin, manager, and regular 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

How can I display Manager; Admin when trying to translate from Enum = 3?

UserModel

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

Enum

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

C# Code

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();
}

//I was thinking something like this:

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

Solution

  • Enum.GetName(typeof(UserRole), enumValue) would give you the Rolename that you are looking for. Here enumValue would be 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();