我试图通过Linq获得所有用户和用户的角色。 这些实体来自ASP.NET MVC身份框架。
我的代码:
var userList = db.Users
.Include("Roles")
.ToList();
我对角色表的结果是" RoleId,UserId"只要 。我想获得为每个用户添加的角色。
我怎么做?
谢谢。
更新答案:
var userList = new List<ManagerUserViewModel>();
foreach (var user in db.Users.ToList())
{
var userRolesId = user.Roles.Select(m => m.RoleId).ToList();
var model = new ManagerUserViewModel()
{
UserId = user.Id,
UserName = user.UserName,
Email = user.Email,
UserInfo = user.UserInfo,
Roles = db.Roles.Where(r => userRolesId.Contains(r.Id))
.ToList()
};
userList.Add(model);
}
答案 0 :(得分:0)
我希望你认为这已经足够了:
// Dummy role name
var name = "Admin";
var rm = new RoleManager<Role>(new RoleStore<Role>(new ApplicationDbContext()));
// Get the role you need (Admin role in this case)
var r = rm.FindByName(name);
// All the user ids that have this role
var userIds = r.Users.Select(u => u.UserId);
// Get all user objects
var users = Db.Users.Where(u => userIds.Contains(u.Id)).ToList();