查询从联接表中获取数据

时间:2019-05-17 18:46:21

标签: c# sql linq entity-framework-core

我有4张桌子:

部门

Id
-----------
1
2
3

员工

Id
----
a
b
c
d
e

Dep2Employee

DepId       EmployeeId
----------- ----------
1           a
1           b
2           c
2           d
3           e

EmployeeHistory

EmplId      ReportType Timestamp
----------- ---------- ----------
1           type1      12.12.12
1           type3      13.12.12
2           type2      14.12.12
3           type2      15.12.12

是否可以在一个LINQ(EF Core)表达式中,为在部门工作并具有给定ID的所有员工按顺序获取所有 type1 的报告通过时间戳记?像GetAllReportsOfType1(string departmentId)

SQL查询的外观也很有趣。

谢谢。

2 个答案:

答案 0 :(得分:0)

SQL:

SELECT * FROM EmployeeHistory His WHERE EmplId in ( SELECT DE.EmployeeId FROM Dep2Employee DE WHERE DE.DepId = '1')
 AND His.ReportType = 'type1'

LINQ

 context.Dep2Employee.Where(a => a.DepId == "1")
                .SelectMany(b => b.EmplId.History.Where(a => a.ReportType == "type1")); 

答案 1 :(得分:0)

  

按照时间戳顺序获取具有给定ID的部门所有员工的所有type1报告。

假设您按照我期望的方式设置导航属性,则可能需要这样的东西:

IQueryable<EmployeeHistory> GetAllReportsOfType1(string departmentId)
{
    return context.EmployeeHistory
        .Where(eh => eh.ReportType == "type1" && eh.Employee.Department.DepId == departmentId)
        .OrderBy(eh => eh.TimeStamp);
}

在不访问模型和数据库的情况下,很难告诉我确切的SQL外观,但是对您来说真的很容易:您只需在生成的IQueryable上调用.ToString()

相关问题