JoseCarlos
JoseCarlos

Reputation: 21

Find users who have a specific role

My code is:

public async Task<ActionResult> Index()
{
    var teaching = db.Teachings.Include(d =>d.Course).Include(d=>d.Group).Include(d => d.User);

    return View(await teaching.ToListAsync());
}

And I want to know how can I filter some roles, I mean, how can I filter only the users who has an specific role, if I can.

I think a possible solution could be ....Include(d => d.Users).Where(...), but I don't know how to compare the role of the user that I am taking, with a specific role.

My roles are teacher, admin or student.

In conclusion, filter only the users whose role is "teacher" .

Upvotes: 2

Views: 2999

Answers (4)

lwschan
lwschan

Reputation: 431

Assuming you are using Identity Framework provided by ASP.net, you can just use the UserManager to achieve that.

In UserManager, it has a function for you, which is GetUsersInRoleAsync(string roleName). This will return you with a list of users in the role.

You could just do

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

And voila, the list will contain all the users with the role that you have specified.

This is assuming if you have initialised _userManager properly.

Upvotes: 2

Munzer
Munzer

Reputation: 2318

You can write one linq to do this for you, select all teachers that associated with users that any of their roles is equal to teacher, which is written like this, for your reference

var teaching = db.Teachings
                    .Include(d =>d.Course)
                    .Include(d=>d.Group)
                    .Include(d => d.User)
                    .Include(d => d.User.Roles)
                    .Where(d => d.User.Roles.Any(r => r.Name == "teacher")));

Upvotes: 1

Pablo
Pablo

Reputation: 34

maybe you can try: db.Teachings.Include(d =>d.Course).Include(d=>d.Group).Include(d => d.User.Where(us=> ur.Role =="teacher"));

I hope this helps!

Upvotes: -1

dericatienza
dericatienza

Reputation: 19

An easy way is to use Identity's UserManager class. It has a UserInRole function which returns a bool. What you can do is iterate through the users and check against this function.

Sample:

foreach(var user in Users)
{
    var isInRole = UserManager.UserInRole(user, "RoleName");
}

Upvotes: 0

Related Questions