【发布时间】: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