Question

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();
    }
} 
Was it helpful?

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top