Search code examples
c#asp.net-mvcentity-frameworkasp.net-identityasp.net-roles

How to filter ICollection<ApplicationUser> on a Role in ASP.NET MVC 5's Identity


I have added 3 roles:

  1. Administrators
  2. Staff
  3. Registered

Now I want to display a list of all Registered users. I'm afraid I'm not getting the Identity system, because I am trying to do something like this:

Spoiler Alert: not working code

var listOfNames = _unitOfWork.UserRepository.All()
                                            .Where(u => u.Roles.Contains("Registered"))
                                            .ToList();

This obviously does not work, so I went searching for an answer. Unfortunately I did not get any. The closest I could find was a post by Scott Allen who mentioned IUserRoleStore which has the following implementations:

  • Add a user to a role
  • Get all the roles for a user
  • Check is a user is in a specific role
  • Remove a user from a role

But still, not getting it :/

I have also tried the methods in this Question, but Roles.Select(r => r.Name).Contains("client") does not work because the Name property can't be found?

How can I get this list of ApplicationUser objects?

Update


Sean's answer helped me to dig a little deeper. I'm not sure this is the best way, but it works for my needs.

var users = context.Users;
var roleUsers = context.Roles.Single(one => one.Name == "Registered").Users;

names = (from r in roleUsers
join u in users on r.UserId equals u.Id
select u.UserName).ToList();

If this is inefficient, I'd love to hear why and how I can improve it.


Solution

  • Assuming AspNetIdentity2.0...I see you are using a repository pattern so in there, could you use the RoleManager:

    var users = RoleManager.Roles.Single(x => x.Name == "Registered").Users;
    

    Unfortunately (and misleadingly) this returns a list of UserRoles but at least you've got the users' UserIds, and from there, can fetch the Users.