计算AspNet.Identity中角色中的用户数(不是成员资格)

时间:2013-12-08 02:05:19

标签: asp.net-identity asp.net-roles

如何最好地计算在AspNet.Identity中具有特定角色的用户数量?通过用户循环比糖蜜慢。这是我非常慢的代码:

public static async Task<string> GetNumUsersInRole(this HtmlHelper helper, string roleName)
{
    int num = 0;
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        using (UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
            await (from u in db.Users select u).ForEachAsync(user =>
                {
                    if (um.IsInRole(user.Id, roleName)) num++;
                }).ConfigureAwait(false);
        }
        return num.ToString();
    }
} 

1 个答案:

答案 0 :(得分:2)

试试这个。

using (ApplicationDbContext db = new ApplicationDbContext())
{                
    IdentityRole myRole= db.Roles.First(r => r.Name == roleName);
    Int32 count = db.Set<IdentityUserRole>().Count(r => r.RoleId == myRole.Id);
    return count;
}