【问题标题】:Query for fetching data from joining table从连接表中获取数据的查询
【发布时间】:2019-05-17 18:46:20
【问题描述】:

我有 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) 表达式中为在 Department 工作的所有员工获取所有具有给定 ID 的 type1 报告,按顺序排列按时间戳?类似GetAllReportsOfType1(string departmentId)

SQL 查询的样子也很有趣。

谢谢。

【问题讨论】:

  • 有没有可能 -- 当然有,使用导航属性甚至会变得非常简单。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    获取部门内所有具有给定 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()

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 2014-01-23
      • 2020-10-22
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多