Continuing my previous question, the accepted answer works perfectly.
However, I only want to have a few roles in my database, say:
Id | Role
1 | AccountOwner
2 | AccountAdmin
3 | AccountUser
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
catch (DbUpdateException ex)
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.