寻找更好的方法来通过 ID 获取项目集合

发布于 2024-11-05 02:57:47 字数 888 浏览 0 评论 0原文

我有一个非常标准的设置,部门和员工之间有多对多的关系。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送舟行 2024-11-12 02:57:47

为什么不使用连接?

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();

Why not use a Join?

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文