Background
I am working on an existing Asp.Net site that uses Database Migrations and Asp.Net Identity.
The site has a folder "Migrations", with a few database migrations. A while ago, I created a "Seed_Only"-migration that doesn't do anything, but simply - as the name implies - executes the Seed method when called thus:
Update-Database -TargetMigration SeedOnly
Irrelevant of whether it's good practice or not, the Seed
method creates new roles if the static helper class RolesName
contains any new roles:
// Iterate all properties of RolesName and create roles if they don't exist
Type type = typeof(RolesName);
foreach (var p in type.GetFields())
{
var v = p.GetValue(null).ToString(); // static classes cannot be instanced, so use null...
if (!context.Roles.Any(x => x.Name.Equals(v)))
{
roleManager.Create(new IdentityRole() { Name = v });
}
}
The Question
We are about to introduce a couple of new roles. I want to make sure each site that runs the app gets it's database updated upon deploy (we deploy using Octopus).
Goals
The following should happen:
- Create new roles if they don't already exist
- Add the new roles to existing users - if the users are member of a previously existing role
This related answer suggests I call Database.SetInitializer(new ApplicationDbInitializer());
from the Constructor of ApplicationDbContext. If I understand the answer correctly, this would solve my need to "continuously keeping the roles up to date", but it does not solve my need for adding existing users to the new roles, as stated in point 2.
How should I go about to achieve my goals?