【问题标题】:Run full EF query on SQL server在 SQL Server 上运行完整的 EF 查询
【发布时间】:2021-04-20 23:26:04
【问题描述】:

我想通过我的 API 返回每个“设备”的最后结果。设备定期与 API 通信,每次通信都有记录。我想提取每个设备的最后一次通信记录。

考虑到表中可能存在的记录数,我想确保在 SQL 中处理查询,而不是提取所有记录并在内存中处理查询的其余部分。

使用LINQ等

            var r = _context.HeartBeat.GroupBy(x => x.SourceDeviceIdent)
            .Select(s => s.OrderByDescending(c => c.HeartBeatDateTimeReceived).First())
            .ToList();

我遇到了错误

.OrderByDescending(c => c.HeartBeatDateTimeReceived)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.

下面给出了所需的输出:

var result = _context.HeartBeat.ToList()
            .GroupBy(g => g.SourceDeviceIdent)
            .Select(s => s.OrderByDescending(o => o.HeartBeatDateTimeReceived).First()).ToList();

但是我假设这是在内存中而不是在 SQL 服务器中处理。

如何将我的查询转换为完全在数据库中处理的查询?

【问题讨论】:

    标签: c# entity-framework asp.net-web-api


    【解决方案1】:

    LINQ 中的这种模式比您尝试的要简单一些:

    var q = from d in db.Devices
            select d.HeartBeats.OrderByDescending(h => h.HeartBeatDateTimeReceived).First();
    
    var r = q.ToList();
    

    翻译为:

      SELECT [t0].[Id], [t0].[DeviceId], [t0].[HeartBeatDateTimeReceived]
      FROM [Devices] AS [d]
      LEFT JOIN (
          SELECT [t].[Id], [t].[DeviceId], [t].[HeartBeatDateTimeReceived]
          FROM (
              SELECT [h].[Id], [h].[DeviceId], [h].[HeartBeatDateTimeReceived], ROW_NUMBER() OVER(PARTITION BY [h].[DeviceId] ORDER BY [h].[HeartBeatDateTimeReceived] DESC) AS [row]
              FROM [HeartBeat] AS [h]
          ) AS [t]
          WHERE [t].[row] <= 1
      ) AS [t0] ON [d].[Id] = [t0].[DeviceId]
    

    【讨论】:

      【解决方案2】:

      存储过程,看看这个链接EF Stored Procedure

      【讨论】:

        猜你喜欢
        • 2011-04-27
        • 2010-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多