首页 > 解决方案 > 从连接表中获取数据的查询

问题描述

我有 4 张桌子:

部门

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

员工

Id
----
a
b
c
d
e

Dep2Employee

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

员工履历

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 查询的样子也很有趣。

谢谢。

标签: c#sqllinqentity-framework-core

解决方案


使用给定 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 的样子,但对您来说真的很容易:您可以简单地调用.ToString()生成的 IQueryable。


推荐阅读