How to obtain a list of all users in a role? Before it was possible with Roles.GetUsersInRole, but with new Identity I can't find anything like this.
For some reason, very nice query suggested above by @ChoptimusPrime did not compile for me in ASP.NET Identity 2.2.1. I have written an extended function:
public static IQueryable<User> GetUsersInRole(DbContext db, string roleName)
{
if (db != null && roleName != null)
{
var roles = db.Roles.Where(r => r.Name == roleName);
if (roles.Any())
{
var roleId = roles.First().Id;
return from user in db.Users
where user.Roles.Any(r => r.RoleId == roleId)
select user;
}
}
return null;
}
for example if you want users list with role "User"
var users = await (from user in _dbContext.Users
join userRole in _dbContext.UserRoles
on user.Id equals userRole.UserId
join role in _dbContext.Roles
on userRole.RoleId equals role.Id
where role.Name == "User"
select user)
.ToListAsync();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With