0

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();
    }
} 
Ungaro
  • 522
  • 6
  • 15

1 Answers1

2

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;
}
jd4u
  • 5,789
  • 2
  • 28
  • 28
  • You've helped me immensely, jd4u. Thank you! I am using async tasks and interestingly the CountAsync doesn't return unless I append the call with .ConfigureAwait(false). – Ungaro Dec 08 '13 at 10:36