我有一个非常标准的设置,在部门和员工之间有多对多的关系。
Departments
---------------
DepartmentID
Name
Employees
---------------
EmployeeID
Name
DepartmentEmployees
-------------------
DepartmentID
EmployeeID
鉴于部门,我想返回该部门的员工名单。这就是我所拥有的:
public partial class Department
{
public List<Employee> GetEmployees()
{
int[] employeeIds = MyDBDataContext.DepartmentEmployees.
Where(de => de.DepartmentID == this.DepartmentID).
Select(de => de.EmployeeID.Value).ToArray();
List<Employee> employees = (from x in MyDBDataContext.Employees
where employeeIds.Contains(x.EmployeeID)
select x).ToList();
return employees;
}
}
这很好用,但我不喜欢进行两次数据库调用。用LINQ做任何其他方法吗?
答案 0 :(得分:2)
为什么不使用加入?
var employees = (from e in MyDBDataContext.Employees
join de in MyDBDataContext.DepartmentEmployees
on e.EmployeeID equals de.EmployeeID
where de.DepartmentID == this.DepartmentID
select e).ToList();