Camilo Terevinto Camilo Terevinto - 1 month ago 4x
C# Question

Mapping Role to static values

Continuing my previous question, the accepted answer works perfectly.

However, I only want to have a few roles in my database, say:

table: Roles

Id | Role
1 | AccountOwner
2 | AccountAdmin
3 | AccountUser

The accepted answer in the question creates a new row in Roles every time a user is registered for an account. Is there any way I can request the Identity system to use the existent roles in the database? Considering the code:

public static async Task<bool> AddAccountAsync(this MyContext context, MyModel model)
Role role = new Role(TrackerRole.Owner);
Account account = new Account(model.AccountCurrency, model.AccountName, model.Description);
UserAccount uc = new UserAccount
User = model.User,
Account = account,
Role = role
await context.SaveChangesAsync();

return true;
catch (DbUpdateException ex)
// LOG
return false;

If possible, I'd like to remove the Role class entirely and substitute it for an Enum.


If you want to substitute it to an enum, the role entity is no longer needed, as is the Role table in the database. Just have the Role property be of type Role (enum) and it will persist as an int to the db. However, this leads to design flaws were you need to update code to add other roles for the future.

About only having the three roles and not adding them needlessly every time: Get the correct role from the db (var role = Context.Roles.Where(...).FirstOrDefault()) and put this into the role property of the useraccount. This way you will be sure all the uac's will point to the correct instances of the roles.