如何最好地统计在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();
}
}
试试这个。
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;
}