Ren*_*ter 1 c# lambda asp.net-identity asp.net-core-mvc
在 ASP.NET Core 2.2 MVC 中,我试图获取特定角色的所有用户的列表。
外汇。名为“Admin”角色的所有用户的列表:
var idsWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();
return(users);
Run Code Online (Sandbox Code Playgroud)
编译器在此处失败“u.Id”:idsWithPermission.Contains(u.Id)
错误:参数 1:无法从“字符串”转换为 Microsoft.AspNetCore.Identity.IdentityUser
这是一个新手问题,所以对于鲨鱼来说可能非常简单:-) 提前非常感谢......
GetUsersInRoleAsync返回对象列表IdentityUser。要获取 ID 列表,您需要访问Id这些对象的属性。
// 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;
Run Code Online (Sandbox Code Playgroud)
.Result请注意,不建议在方法上使用async,因为它可能导致死锁。相反,使用await并制作你的方法async。
另请注意,根据您的设置,如果ApplicationUser继承IdentityUser并且身份系统配置正确,GetUsersInRoleAsync则已经返回ApplicationUser对象,您只需将它们转换为正确的类型:
// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = usersWithPermission.OfType<ApplicationUser>();
return users;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1694 次 |
| 最近记录: |