asp.net-identityasp.net-roles

Count the number of Users in a Role in AspNet.Identity (not Membership)


How to best count the number of users that have a specific role in AspNet.Identity? Looping through the users is slower than molasses. Here is my VERY SLOW code:

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

Solution

  • Try this.

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