My schema is a fairly straight-forward membership and roles schema:
Users table:
UserId (PK)
UserName
etc...
Roles table:
RoleId (PK)
RoleName
UsersInRole table
UserId (FK to Users table)
RoleId (FK to ROles table)
So, we’ve got the many-to-many table UsersInRole along with the other two tables. When I add the schema into EF, the generated ORM code (and the EF designer) only shows Users and Roles (no problem, EF manages the many-to-many).
So, here’s my question. I want to list all the users who do not have the role “Super Admin”. Seems like a simple problem, just use a SelectMany in EF. The problem is a user may have multiple roles, one of which is “Super Admin”. If I use the SelectMany (like below), I will still get those users who have “Super Admin” in addition to other roles. The SelectMany only works if the user has one role and that role is “Super Admin”
I’ve tried to put together SQL to work from that to the Linq-to-EF, but haven’t had any luck doing that either.
var usrQry = context.Roles.Where(r => r.RoleName != "Super Admin")
.SelectMany(r => r.Users);
Any help is appreciated – thanks in advance.
Your query will also return the same users multiple times. You are better to go back to your original statement and try to make the code look more like it.
Your statement was:
So here is the code to do that.
in LINQ syntax: