C# 筛选dbcontext对象中的记录

C# 筛选dbcontext对象中的记录,c#,asp.net-mvc,linq,entity-framework-6,C#,Asp.net Mvc,Linq,Entity Framework 6,我使用EntityFramework6数据库优先的方法 我有三张桌子: 1.系统角色 2.MasterAppMenu 3.员工手册 一个SystemRole可以有多个MasterAppMenu,因此这是一对多关系 这是我想做的 private myEntities entities = new myEntities(); var roleMenuMappings = entities.SystemRoles.Where( x => x.EmployeeRoleMenuMappings.Se

我使用EntityFramework6数据库优先的方法

我有三张桌子:

1.系统角色

2.MasterAppMenu

3.员工手册

一个SystemRole可以有多个MasterAppMenu,因此这是一对多关系

这是我想做的

private myEntities entities = new myEntities();
var roleMenuMappings = entities.SystemRoles.Where( x => x.EmployeeRoleMenuMappings.Select(  m => m.MasterAppMenu.ParentMenuId==null  )  );
var roleMenuList = await roleMenuMappings.ToListAsync();
return View(roleMenuList);
我想筛选MasterAppMenu表中ParentMenud为null的SystemRoles记录。系统角色具有具有此MasterAppMenu属性的Icollection对象EmployeeRoleMenuMappings


请告诉我如何实现这一点,我知道这可以在视图端完成,但如果您需要所有具有空MasterAppMenu ParentMenuId的EmployeeRoleMenuMappings,我只想在控制器端完成:

var roleMenuMappings = entities.EmployeeRoleMenuMappings
    .Where(m => m.MasterAppMenu.ParentMenuId == null);
您还可以从系统角色级别执行此操作:

var systemRolesWithMenuMappings = entities.SystemRoles
    .Where(x => x.EmployeeRoleMenuMappings.Any(m => m.MasterAppMenu.ParentMenuId == null);
或主应用程序菜单级别:

var roleMenuMappings = entities.MasterAppMenu.Where(w => w.ParentMenuId == null);
基本上,您可以使用Where()来过滤记录。在Where()中使用Any(),因为它返回谓词或布尔值


这些查询将仅显示具有空值的项。如果您只想要没有空值的项目,只需将其更改为
!=空
在代码中。

感谢hep,但不起作用:首先,它在m=>m.MasterAppMenu.Any(a=>a.ParentMenuId==null)处给出错误,无法识别任何函数,甚至我也喜欢这个entities.SystemRoles.Where(x=>x.employeerolemmenumappings.Any(m=>m.MasterAppMenu.ParentMenuId==null));它正在运行,但没有过滤recordsAny()和Where()都在系统中。Linqyes,但我想任何可以应用的集合对象我已经尝试过了,它没有给出任何错误,但甚至不过滤任何记录请澄清您所说的
我想过滤ParentMenuId
字段中为空值的MasterAppMenu的记录。我已在代码表单下编辑了我的问题,因此每个MasterAppMenu只有一个ParentMenuId?是,我在你的第二个答案中告诉过你,如果我删除了其中的任何一个,它不会显示错误,但它也不会过滤。我编辑了我的答案来更正它!