使用LINQ和存储过程获取对象

本文关键字:获取 取对象 存储过程 LINQ 使用 | 更新日期: 2023-09-27 17:57:36

我有一个存储过程,它以以下格式返回数据:

EmployeeID | DepartmentID
---------------------
1 | 1
2 | 1
3 | 2
4 | 4
5 | 4

我得到的结果是这样的:

List<spResult> results = DataContext.sp().ToList();

我想根据存储过程返回的数据获得某个部门的员工列表。类似于:

int departmentId = 1;
List<Employee> employees = (from e in DataContext.Employees
                            //where...
                            select e).ToList();

如何格式化where子句以从具有给定DepartmentID的结果集中获取EmployeeID?

使用LINQ和存储过程获取对象

怎么样:

List<spResult> results = DataContext.sp().ToList();
int departmentId = 1;
var departmentEmployees = from de in results
                          where de.DepartmentId == departmentId
                          select de.EmployeeID;
List<Employee> employees = (from e in DataContext.Employees
                            where departmentEmployees.Contains(e.ID)                            
                            select e).ToList();

您可以获得密钥的子集:

var empKeys = results.Where(i => i.DepartmentID = departmentID);

然后在查询中使用此列表,如:

List<Employee> employees = (from e in DataContext.Employees
                            where empKeys.Contains(e.EmployeeID)
                            select h).ToList();

HTH。

您还应该能够执行以下操作:

List<Employee> employees = DataContext.Employees.Where(e => empKeys.Contains(e.EmployeeID)).ToList()