Get list of users with assigned roles in asp.net identity 2.0 Get list of users with assigned roles in asp.net identity 2.0 asp.net asp.net

Get list of users with assigned roles in asp.net identity 2.0


Not an expert, but ...

There seemed to be no built in funcionality for this in Identity and I could not get it work from built in Roles also (it seems to not work with claims based Identity).

So I ended up doing something like this:

var users = context.Users            .Where(x => x.Roles.Select(y => y.Id).Contains(roleId))    .ToList();
  • x.Roles.Select(y => y.Id) gets a list of all role ids for user x
  • .Contains(roleId) checks if this list of ids contains necessary roleId


I find the role by the role name input. After, I find list users by id of the role.

public List<ApplicationUser> GetUsersInRole(string roleName){ var roleManager =   new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new  ApplicationDbContext())); var role = roleManager.FindByName(roleName).Users.First(); var usersInRole =   Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList(); return usersInRole;}


If you want to avoid using the context directly you can use the RoleManager with the following snippet

roleManager.FindByName("Administrator").Users

or

roleManager.FindByName("CanEdit").Users

For a short discussion about this topic have a look at the this thread