Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all users within a role. ASP.NET Identity

I can get all users like this

var users = UserManager.Users.ToList();

I can find a role like this

var role = db.Roles.SingleOrDefault(m => m.Name == "User");

I want to list all users with the role name "User" in the AspNetRoles table (I have User and Admin).

var role = db.Roles.SingleOrDefault(m => m.Name == "User");
var usersInRole = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id)).ToList();

return View(usersInRole);

I get the role in var role but userInRole gives me Count = 0 when I debug. No compile errors.

like image 992
Anders Avatar asked Mar 29 '16 09:03

Anders


1 Answers

You can use bellow code for retrieve all users in specific role (Identity 2.x.x):

var users = await _userManager.GetUsersInRoleAsync("RoleName");

or for synchronize usage:

var users = _userManager.GetUsersInRoleAsync("RoleName").Result;
like image 137
Sajad Afaghiy Avatar answered Sep 28 '22 14:09

Sajad Afaghiy