Abh*_*nyu 29 asp.net asp.net-mvc asp.net-mvc-4 asp.net-identity asp.net-identity-2
我有一个列出角色的下拉列表框.我想获得具有该角色的用户列表.我的意思是"管理员"角色或"CanEdit"角色的用户列表.这是我的代码:
public IQueryable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
GetRolesToUsers([Control] string ddlRole)
{
//ddlRole returns role Id, based on this Id I want to list users
var _db = new ApplicationDbContext();
IQueryable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser> query = _db.Users;
if (ddlRole != null)
{
//query = query.Where(e => e.Claims == ddlRole.Value); ???????
}
return query;
}
Run Code Online (Sandbox Code Playgroud)
请帮忙.
更新的代码(仍然错误)
public List<IdentityUserRole> GetRolesToUsers([Control]string ddlRole)
{
var roleManager =
new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var users = roleManager.FindByName("Administrator").Users.ToList();
return users;
}
Run Code Online (Sandbox Code Playgroud)
错误:当ItemType设置为"Microsoft.AspNet.Identity.EntityFramework.IdentityUser"时,Select方法必须返回"IQueryable"或"IEnumerable"或"Microsoft.AspNet.Identity.EntityFramework.IdentityUser"之一.
我尝试了各种铸件,但没有一个帮助.
更新(工作解决方案)
感谢chris544,他的想法帮助我解决了这个问题.这是工作方法: -
public List<ApplicationUser> GetRolesToUsers([Control]string ddlRole)
{
var context = new ApplicationDbContext();
var users =
context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(ddlRole)).ToList();
return users;
}
Run Code Online (Sandbox Code Playgroud)
chr*_*544 38
不是专家,但......
在Identity中似乎没有内置的功能,我也无法从内置的Roles中获得它的功能(它似乎不适用于基于声明的Identity).
所以我最终做了这样的事情:
var users = context.Users
.Where(x => x.Roles.Select(y => y.Id).Contains(roleId))
.ToList();
Run Code Online (Sandbox Code Playgroud)
x.Roles.Select(y => y.Id) 获取所有角色ID的列表 user x.Contains(roleId) 检查此id列表是否必要 roleId小智 12
我通过角色名称输入找到角色.之后,我通过角色的id找到列表用户.
public List<ApplicationUser> GetUsersInRole(string roleName)
{
var roleManager =
new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = roleManager.FindByName(roleName).Users.First();
var usersInRole =
Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
return usersInRole;
}
Run Code Online (Sandbox Code Playgroud)
如果要避免直接使用上下文,可以将RoleManager与以下代码段一起使用
roleManager.FindByName("Administrator").Users
Run Code Online (Sandbox Code Playgroud)
要么
roleManager.FindByName("CanEdit").Users
Run Code Online (Sandbox Code Playgroud)
有关此主题的一个简短的讨论有一个看看这个线程
| 归档时间: |
|
| 查看次数: |
46799 次 |
| 最近记录: |