I have a database with a table called ‘Roles’, with ‘Id’ and ‘RoleName’ columns.
These are the rows in the table:
- GUID1 Administrator
- GUID2 System
- GUID3 Technician
- GUID4 Normal
A user in the ‘User’ table can have several roles to it.
I would like to have LINQ code to check if a specific user has the role ‘Technician’.
This is my code for now :
using (MyDbEntities entities = new MyDbEntities())
{
User user = entities.Users.Where(u => u.Id == userIdToFetch).Single();
// Check if user is 'Technician'
if (user.Roles.Any(role => role.Name == "Technician") == true)
{
// user IS technician - do work here
}
}
My problem is – I don’t want to hard-code the string “Technician” to my code,
because maybe one day the name of the role in the database will change to “Tech”.
I have looked at using ‘Resources’, but that is no good, because changing a string in a resource means recompiling the project.
I do not want to add a section to the configuration file that holds this information,
because it seems to me as over-kill…
Any suggestions ?
I’d use a table where I store all the different roles and associate the ID of the role with the role ID of the user. That way you can change the name of the role as much as you like as long as the role ID stays the same.