寻找更好的方法来通过 ID 获取项目集合
我有一个非常标准的设置,部门和员工之间有多对多的关系。
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 实现此目的吗?
I have a pretty standard setup, with a many-to-many relationship between Departments and Employees.
Departments
---------------
DepartmentID
Name
Employees
---------------
EmployeeID
Name
DepartmentEmployees
-------------------
DepartmentID
EmployeeID
Given a Department, I'd like to return a List of Employees for that Department. Here's what I have:
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;
}
}
This works fine, but I don't like making two database calls. Any other way to do this with LINQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不使用连接?
Why not use a Join?