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

时间:2011-05-25 19:58:07

标签: c# asp.net linq linq-to-sql

我有一个以这种格式返回数据的存储过程:

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

我得到的结果如下:

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

我想根据存储过程返回的数据获取某个部门的Employees列表。类似的东西:

int departmentId = 1;

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

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

3 个答案:

答案 0 :(得分:2)

怎么样:

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

答案 1 :(得分:1)

您可以获得密钥的子集:

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。

答案 2 :(得分:1)

您还应该能够做到这样的事情:

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