Reputation:
There are three tables which are related to roles.
UserId
dataRoleName
and RoleId
UserId
and RoleId
. But for some reason I couldn't access to this table directly (like db.UserRoles
).So what I'am trying to do is avoid listing the users which are in the Admin role.
My code is like this:
return View(db.Users.OrderBy(e => e.UserName)
.ToPagedList(pageNumber, pageSize));
I think I should make something like this but I always get errors when I do it this way
return View(db.Users.Where(e => e.Roles.Where(r => r.RoleId != "1"))
.OrderBy(e => e.UserName)
.ToPagedList(pageNumber, pageSize));
// suppose that the RoleId of Admin is 1
Upvotes: 0
Views: 1420
Reputation:
Try this:
const int adminRoleId = 1;
var query = db.Users.Where(user => !user.Roles
.Any(role => role.Id
== adminRoleId));
return View(query.OrderBy(e => e.UserName)
.ToPagedList(pageNumber, pageSize));
I think that in your case the problem is caused by r.RoleId != "1"
, I think that RoleId
is of int
type. What;s more, the expression Where(e => e.Roles.Where(r => r.RoleId != "1"))
is invalid. Expression tree passed into first Where
should return bool
for specified r
(it is user in your context) but you are returniing collection of roles different than admin (instead of mentioned bool
).
Upvotes: 0
Reputation: 13399
return View(db.Users.Where(e => e.Roles.All(r => r.RoleId != "1"))
.OrderBy(e => e.UserName).ToPagedList(pageNumber, pageSize));
// Suppowse that the RoleId of Admin is 1
Use the .All
extension
Or db.Users.Where(u=>!u.Roles.Any(r=>r.RoleId == "1"))
Upvotes: 0