我想要得到:
- 列表
ApplicationUsers
谁在扮演角色"NormalUser"
对任何人 - 全部列表
ApplicationUsers
仅限管理员。
我这样做了:
// GET: ApplicationUsers
public ActionResult Index() {
// if you are Admin you will get all users
if (User.IsInRole("Admin"))
return View(db.Users.ToList());
//if you are somebody else(not Admin) you will see only list of NormalUsers
//HERE I GET ERROR
var list = db.Users.Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList(); // here I get error
return View(list);
}
上面的UserManager内部代码是:UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
但不幸的是我的 LINQ 表达式不正确。我收到错误:
LINQ to Entities does not recognize the method 'Boolean IsInRole[ApplicationUser,String](Microsoft.AspNet.Identity.UserManager`2[WebApplication2.Models.ApplicationUser,System.String], System.String, System.String)' method, and this method cannot be translated into a store expression.
问题:如何正确获取角色"NormalUser"
的用户列表?
最佳答案
数据库不支持 UserManager.IsInRole 函数,但如果您的应用程序可以承受在应用过滤器之前从数据库中拉回整个 User 表的重量,那么您只需在 Users 表引用之间添加一个 ToList和你的Where过滤器,即
var list = db.Users.ToList().Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList();
关于asp.net-mvc - 如何通过LINQ表达式从数据库中获取处于特定角色的所有应用程序用户的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25938579/