Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity: get all users in a role

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.

like image 338
graycrow Avatar asked Oct 21 '13 09:10

graycrow


2 Answers

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;
}
like image 76
Boris Zinchenko Avatar answered Oct 12 '22 10:10

Boris Zinchenko


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();
like image 45
Omid Soleiman Avatar answered Oct 12 '22 10:10

Omid Soleiman