【问题标题】:How to count all users with a specific role in ASP.NET Core 2.0如何计算 ASP.NET Core 2.0 中具有特定角色的所有用户
【发布时间】:2018-04-20 16:47:45
【问题描述】:

我正在使用 Identity 开发一个 Asp.net core 2.0 项目。我的项目使用核心 1.1 创建和开发,一段时间后迁移到核心 2.0。 迁移到核心 2.0 后一切都很好,但在项目的一部分中,我需要让所有用户都具有特定角色。 在 Asp.Net Core 1.1 中,我使用以下代码计算所有特定角色的数量:

r.Users.Count

完成的代码:

    public IActionResult Index()
    {
        List<ApplicationRoleViewModel> model = new List<ApplicationRoleViewModel>();
        model = _roleManager.Roles.Select(r => new ApplicationRoleViewModel
        {
            Id = r.Id,
            Name = r.Name,
            Description = r.Description,
            NumberOfUsers = r.Users.Count
        }).ToList();

        return View(model);

    }

和:

public class ApplicationRoleViewModel
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public int NumberOfUsers { get; set; }
}

但是核心 2.0 中没有 Users 对象。 我也看到了这个question,但我无法解决我的问题。 现在如何计算 ASP.NET Core 2.0 中具有特定角色的所有用户?

【问题讨论】:

    标签: asp.net-core asp.net-core-2.0 identity


    【解决方案1】:

    UserRoles 集合存储用户之间的所有引用以及他们所属的角色。你可以这样做:

    var allUserRoles = _identityDb.UserRoles.ToList();
    model = _roleManager.Roles.Select(r => new ApplicationRoleViewModel
    {
        Id = r.Id,
        Name = r.Name,
        Description = r.Description,
        NumberOfUsers = allUserRoles.Count(ur => ur.RoleId == r.Id)
    }).ToList();
    

    请记住,这是非常低效的,因为它在您的操作中而不是在数据库中进行计数。理想情况下,这将由生成的 sql 查询直接完成,但如果您不处理大量用户/角色,这个简单的解决方案应该可以正常工作。


    如果您已经有一个自定义的 IdentityRoleUserRole 模型,您应该能够添加允许您使用 IdentityDb.Roles.Include() 来基于 RoleId 引用 UserRoles 的属性。或者,您可以使用类似于下面的查询来执行自定义 sql 命令,该命令将返回所需的信息。请记住,您的身份数据库的列或表可能在此处有所不同。

    List<ApplicationRoleViewModel> vm = new List<ApplicationRoleViewModel>();
    
    using (var dbConnection = _identityDb.Database.GetDbConnection())
    using (var dbCommand = dbConnection.CreateCommand())
    {
        dbCommand.CommandText =
            @"SELECT 
                r.Id,
                r.Name,
                r.Description
                Count(ur.UserId)  as NumberOfUsers
            FROM AspNetRoles r
            FULL OUTER JOIN AspNetUserRoles ur ON r.Id = ur.RoleId
            GROUP BY r.Id, r.Name, r.Description";
    
        dbConnection.OpenAsync().Wait();
        using (var result = dbCommand.ExecuteReader())
        {
            while (result.Read())
            {
                vm.Add(new ApplicationRoleViewModel()
                {
                    Id = result.GetString(0),
                    Name = result.GetString(1),
                    Description = result.GetString(2),
                    NumberOfUsers = result.GetInt32(3)
                });
            }
        }
    }
    

    【讨论】:

    • 能不能稍微解释一下更好的方法或者介绍一个链接?
    • 您不能简单地获取所需的Role,然后执行await _context.UserRoles.CountAsync(ur =&gt; ur.RoleId == theRoleImLookingFor.Id); 之类的操作
    【解决方案2】:

    如果正确配置了 asp.net 身份,您可以将 UserManager 和 RoleManager 注入到您的控制器中。

    public class AccountController : Controller
    {
        private UserManager<IdentityUser> userManager;
        private RoleManager<IdentityRole> roleManager;
    
        public AccountController(UserManager<IdentityUser> userMgr,
        RoleManager<IdentityRole> roleMgr) 
        {
          userManager = userMgr;
          roleManager = roleMgr;
        }
    }
    

    现在,您可以在 userManager 上调用 GetUsersInRoleAsync("myRole") 以在您的操作方法中获取 myRole 中的所有用户。

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 1970-01-01
      • 2021-02-24
      • 2021-01-12
      • 2016-06-18
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多