Seed Roles (RoleManager vs RoleStore)
Asked Answered
C

1

2

Through looking at the posts here, I've seen two different ways of creating ASP.NET Identity roles through Entity Framework seeding. One way uses RoleManager and the other uses RoleStore. I was wondering if there is a difference between the two. As using the latter will avoid one less initialization

string[] roles = { "Admin", "Moderator", "User" };

// Create Role through RoleManager

var roleStore = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(roleStore);

foreach (string role in roles)
{
    if (!context.Roles.Any(r => r.Name == role))
    {
       manager.Create(new IdentityRole(role));
    }

// Create Role through RoleStore

var roleStore = new RoleStore<IdentityRole>(context);

foreach (string role in roles)
{
    if (!context.Roles.Any(r => r.Name == role))
    {
       roleStore.CreateAsync(new IdentityRole(role));
    }
}
Cleora answered 21/10, 2016 at 18:53 Comment(0)
L
3

In your specific case, using both methods, you achieve the same results.

But, the correct usage would be:

var context = new ApplicationIdentityDbContext();
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);

string[] roles = { "Admin", "Moderator", "User" };

foreach (string role in roles)
{
     if (!roleManager.RoleExists(role))
     {
           roleManager.Create(new IdentityRole(role));
     }
}

The RoleManager is a wrapper over a RoleStore, so when you are adding roles to the manager, you are actually inserting them in the store, but the difference here is that the RoleManager can implement a custom IIdentityValidator<TRole> role validator.

So, implementing the validator, each time you add a role through the manager, it will first be validated before being added to the store.

Lorin answered 21/10, 2016 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.