Reputation: 123
In ASP.NET Core 2.2 MVC I'm trying to get a list of all users in a specific role.
Fx. list of all users in role named "Admin":
var idsWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();
return(users);
Compiler fails "u.Id" here: idsWithPermission.Contains(u.Id)
Error: Argument 1: Cannot convert from "string" to Microsoft.AspNetCore.Identity.IdentityUser
This is a newbie questions, so might be very simple for a shark :-) Thanks a lot in advance...
Upvotes: 1
Views: 1986
Reputation: 28499
GetUsersInRoleAsync
returns a list of IdentityUser
objects. To get a list of IDs, you need to access the Id
property of these objects.
// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
// Then get a list of the ids of these users
var idsWithPermission = usersWithPermission.Select(u => u.Id);
// Now get the users in our database with the same ids
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();
return users;
Note that using .Result
on an async
method is not advised, because it can lead to deadlocks. Instead use await
and make your method async
.
Also note that depending on your setup, if ApplicationUser
inherits from IdentityUser
and the identity system is correctly configured, GetUsersInRoleAsync
will already return ApplicationUser
objects and you only need to cast them to the correct type:
// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = usersWithPermission.OfType<ApplicationUser>();
return users;
Upvotes: 5