I have added 3 roles:
- Administrators
- Staff
- 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.