【发布时间】:2013-06-03 22:43:32
【问题描述】:
我需要帮助过滤实体框架 (EF) 导航上的 LINQ 查询 财产。这些表是首先创建的(不是代码优先的)。
对于这个问题,让我们使用 The Office 中的角色。
假设我有以下表格和列:
Offices
Id
Name
Location
Employees
Id
Name
EmployeeTypes
Id
Description
Employees_EmployeeTypes
Id
EmployeeId
EmployeeTypeId
表格有以下数据:
Offices
1 North Branch PA
2 South Branch FL
3 East Branch NY
Employees
1 Jim
2 Pam
3 Oscar
4 Dwight
5 Michael
6 Angela
7 Kevin
8 Stanley
EmployeeTypes
1 Manager
2 Salesman
3 Assistant
4 Receptionist
5 Accountant
Employees_EmployeeTypes
1 1 2
2 2 4
3 3 5
4 4 2
5 5 1
6 6 5
7 7 5
8 8 2
使用“从数据库更新模型”将这些表引入 EF Visual Studio 中的功能。
所有实体的命名与表名完全相同,并且实体集是 复数。
Entity Name Entity Set Name
Office Offices
Employee Employees
EmployeeType EmployeeTypes
Employees_EmployeeTypes 表是一个联结表(多对多),将 转换为 EF 中的导航属性并命名为“EmployeeTypes”。这是 其用法示例:
var employeeTypes = dbContext.Employees.Find(1).EmployeeTypes;
现在我们已经完成了设置,让我们来回答问题。使用 LINQ,我怎么能 使用导航属性选择所有作为推销员的员工 “员工类型”?在 SQL 中,它看起来像这样:
select e.Id, e.Name
from Employees e
join Employees_EmployeeTypes e_et on e_et.EmployeeId = e.Id
join EmployeeTypes et on et.Id = e_et.EmployeeTypeId
where et.Id = 2
【问题讨论】:
标签: c# sql linq entity-framework