簡體   English   中英

尋找一種更好的方法來通過 ID 獲取項目集合

[英]Looking for a better way to get a collection of items by 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 還有其他方法嗎?

為什么不使用聯接?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM