LINQ - 查询通过多对多关系过滤的列表

时间:2010-04-21 16:32:46

标签: linq

请原谅我的问题的背景,因为我不知道如何确切地说出来。

为了不进一步复杂化,这是我的业务要求:“将我们所属的所有员工带回部门”X“。

因此,当我查看此内容时,它将显示属于该部门的所有员工。

这是我的环境:带有Entity Framework 1.0的Silverlight 3和WCF Data Services 1.0。我能够加载和绑定各种列表(简单),没问题。我觉得我的环境不重要,这就是为什么我觉得这比LINQ问题更重要。

我的问题是我有3个表链接的场景,即实体(集合)。

例如,我在我的EDM中有这个:Employee - EmployeeProject - Project。

以下是数据库中的表格设计:

Employee (table1)
-------------
EmployeeID (PK)
FirstName
other Attributes ...

EmployeeProject (table2)
-------------
EmployeeProjectID (PK)
EmployeeID (FK)
ProjectID (FK)
AssignedDate
other Attributes ...

Project (table3)
-------------
ProjectID (PK)
Name
other Attributes ...

以下是Entity Framework的EDM设计:

------------------------
Employee (entity1)
------------------------
(Scalar Properties)
-------------------
EmployeeID (PK)
FirstName
other Attributes ...
-------------------
(Navigation Properties)
-------------------
EmployeeProjects

------------------------
EmployeeProject (entity2)
------------------------
(Scalar Properties)
-------------------
EmployeeProjectID (PK)
AssignedDate
other Attributes ...
-------------------
(Navigation Properties)
-------------------
Employee
Project

------------------------
Project (entity3)
------------------------
(Scalar Properties)
-------------------
ProjectID (PK)
Name
other Attributes ...
-------------------
(Navigation Properties)
-------------------
EmployeeProjects

到目前为止,我只能做到:

var filteredList = Context.Employees
    .Where(e => e.EmployeeProjects.Where(ep => ep.Project.Name == "ProjectX"))

注意:我在约翰的帖子后更新了查询的语法。

如您所见,我只能查询相关实体(EmployeeProjects)。我想要的就是能够从Employee实体过滤到Project。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你正在寻找这样的事情:

var filteredList = employees.Where(e => e.EmployeeProjects.Count(ep => ep.Project.Name == "Some project name") > 0)