种子角色(RoleManager与RoleStore) [英] Seed Roles (RoleManager vs RoleStore)

本文介绍了种子角色(RoleManager与RoleStore)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过查看此处的帖子,我已经看到了通过实体框架种子创建ASP.NET身份角色的两种不同方式.一种方式使用RoleManager,另一种方式使用RoleStore.我想知道两者之间是否有区别.因为使用后者将避免较少的初始化

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));
    }
}

推荐答案

在您的特定情况下,使用这两种方法,您将获得相同的结果.

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

但是,正确的用法是:

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));
     }
}

RoleManagerRoleStore的包装,因此,当您将角色添加到经理时,实际上是将它们插入商店,但是区别在于RoleManager可以实现自定义IIdentityValidator<TRole> 角色验证器.

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.

因此,实施验证器时,每次通过 manager 添加角色时,都会先对其进行验证,然后再将其添加到商店.

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

这篇关于种子角色(RoleManager与RoleStore)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆