Get all users within a role. ASP.NET Identity
Asked Answered
L

5

5

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.

Laurelaureano answered 29/3, 2016 at 9:24 Comment(0)
T
9

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").GetAwaiter().GetResult();
Ticon answered 24/6, 2018 at 17:34 Comment(0)
O
2
var usersInRole = db.Users.Where(m => m.Roles.RoleId == role.Id)).ToList();

You search through all the users and returns the ones that fit a specific role id

Opalopalesce answered 29/3, 2016 at 9:32 Comment(4)
Please explain your answer in words tooMaynor
Done. Really. Its rather self explanatoryOpalopalesce
Please select as answer if this helpedOpalopalesce
This gives me an error on RoleId in m.Roles.RoleId and I can't find Id or RoleId in VS intellisense.Laurelaureano
S
1

Have you tried to use navigation properties Lazy Loading ?

var role = db.Roles.SingleOrDefault(m => m.Name == "User");
var usersInRole = role.Users;
Shig answered 29/3, 2016 at 9:32 Comment(1)
Error "The model item passed into the dictionary is of type 'System.Collections.Generic.List1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Dignitana.Models.ApplicationUser]'."Laurelaureano
V
0

you can use Linq expression base query like below :

var roleUserIdsQuery=from role in db.Roles 
                where role.Name=="User"
                from user in role.Users
                select user.UserId;
var users=db.Users.Where(u=>roleUserIdsQuery.Contains(u.Id)).ToList();
Volscian answered 29/3, 2016 at 18:29 Comment(0)
S
0

For Identity 2.0... and .NET Framework 4.5+

Check IdentityConfig.cs to make sure that the role manager is configured correctly.

var roleManager = HttpContext.GetOwinContext().GetUserManager();

var users = roleManager.FindByName("Administrator").Users.ToList();

Shelly answered 30/3, 2023 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.