问题
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));
}
}
回答1:
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.
来源:https://stackoverflow.com/questions/40183642/seed-roles-rolemanager-vs-rolestore