Counting the Number of Users in a Role

Counting the number of users in a role in Identity seemed to me to be a very straight forward task. It turned out to be a little more challenging than I had expected but once I figured out the correct linq statement it was rather easy to get working.

To start with I added the AspNetUsers, AspNetRoles, and AspNetUserRoles tables to my DbContext so that I could access these tables easily through linq. I created an instance of my DbContext layer inside the RolesAdminController class in the Controllers/RolesAdminController.cs file.

public class RolesAdminController : Controller{
     private DbNameEntities db = new DbNameEntities();
     // Code Omitted for Brevity

Then in the Index() ActionResult I added the following code to calculate the number of users in each role, stored those values in a dictionary collection and passed the dictionary to the view using a ViewBag object.

public ActionResult Index(){
     var Roles = RoleManager.Roles;
     Dictionary<string, int> roleCount = new Dictionary<string, int>();
     foreach(var role in Roles){
          var ct = db.AspNetUsers.Where(x => x.AspNetRoles.Select(y => y.Id).Contains(role.Id)).Count();
          roleCount.Add(role.Name, ct);
     ViewBag.RoleCount = roleCount;
     return View(RoleManager.Roles);

Finally on the view I added a column to the table and used the current role name (dictionary key) which output the number of users in that role (dictionary key).

@foreach (var item in Model){
          <td>@Html.DisplayFor(modelItem => item.Name)</td>
          <!-- Code Omitted for Brevity -->

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *