Reputation: 161
I created a new MVC project with ASP.NET Identity as my authentication and authorization framework, using the individual authentication method. I successfully added 3 roles to the application: Admin
, Customer
, Owner
.
Now I've made three action methods in my HomeController
: "All Admins", "All Customers", "All Owners". How can I, in each action method, display the users that are in each role and their total count? Meaning when I click on "All Admins" it display all users with admin roles, and the same with the "All Customers" and "All Owners" actions.
Upvotes: 4
Views: 3898
Reputation: 3322
I could not find the SingleAsync
method of the RoleManager
as described by
CodeCaster.
So there is another way to get the role by name:
string roleName = "Employee";
var role = await RoleManager.FindByNameAsync(roleName);
and then get the users:
var users = UserManager.Users.Where(x=>x.Roles.Any(y=>y.RoleId==role.Id))
.Select(x => new {UserId = x.Id,FullName = x.FullName });
Upvotes: 1
Reputation: 1058
I had similar problem so I used something like this:
var administrators = from role in _roleManager.Roles
from userRoles in role.Users
join user in _userManager.Users on userRoles.UserId equals user.Id
where role.Name == "Administrator"
select new UserVm()
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email,
Role = role.Name
};
Upvotes: 2
Reputation: 151594
You can use the RoleManager
and UserManager
. The latter lets you query on RoleId only, so you'll have to look up the Role first:
// Look up the role
string roleName = "Admin";
var role = await _roleManager.Roles.SingleAsync(r => r.Name == roleName);
// Find the users in that role
var roleUsers = _userManager.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id));
Now you can send the roleUsers
to a view that displays the users and their total count.
Upvotes: 9