Seed Roles (RoleManager vs RoleStore)

自古美人都是妖i 提交于 2020-06-28 06:46:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!