代码之家  ›  专栏  ›  技术社区  ›  Damo

在SQL server上运行完整的EF查询

  •  0
  • Damo  · 技术社区  · 4 年前

    我想通过我的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服务器上处理。

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

    0 回复  |  直到 4 年前
        1
  •  0
  •   David Browne - Microsoft    4 年前

    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
  •  0
  •   JKC    4 年前

    存储过程,请查看此链接 EF Stored Procedure