Reputation: 2519
I have added 3 roles:
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:
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?
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.
Upvotes: 0
Views: 2754
Reputation: 1497
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' UserId
s, and from there, can fetch the Users
.
Upvotes: 2