Query many-to-many return null with two double many-many relationship

I have a list of item, in which contain item that can be viewed by user with specific role or user who has been allowed to view that item. I try query a list of item for a user base on their role and their Id but it give ma null result. What did I do wrong here?

var query = from menuItem in _db.MenuItems
where menuItem.MenuRoles.Any(m => m.RoleId == role.Id)
where menuItem.MenuUsers.Any(m => m.UserId == userId)
select menuItem;

Answer

You don’t want a double where clause, you want or:

var query = from menuItem in _db.MenuItems
where menuItem.MenuRoles.Any(m => m.RoleId == role.Id) || menuItem.MenuUsers.Any(m => m.UserId == userId)
select menuItem;

If the first where doesn’t find any, then your second where-clause isn’t going to find anything in that result. EDIT: I just saw it’s says their role and their Id. If so replace || with &&.

Leave a Reply

Your email address will not be published. Required fields are marked *