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)
@Html.DisplayFor(modelItem => item.Name)</td>
<!-- Code Omitted for Brevity -->

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s