2

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...

1 Answers1

1

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();
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ashok
  • 743
  • 4
  • 13
  • Do I need to import a namespace for Enum.GetName? I can't seem to be able to use it – Jenny From the Block Apr 10 '19 at 00:25
  • It should be under System namespace – Ashok Apr 10 '19 at 00:30
  • Sorry to bother you Ashok. What if I have Enum = 3 which represents a combination of both Manager and Admin. How can I display `Manager; Admin` (separated by semi-colon)? – Jenny From the Block Apr 10 '19 at 02:26
  • I do not think it is the right idea or right design to have a additional enum or additional value in the database just to indicate that user has two roles.If a user is both Manager and Admin he should have two rows (1 and 2) in the database and not 3.So when you query this user you would have an array of roles which can be seperated by a semicolon. – Ashok Apr 10 '19 at 14:23