如何最好地计算在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();
}
}
答案 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;
}