[英]Entity Framework select most recent record for each type of record
I have a table called values that looks like this:我有一个名为 values 的表,如下所示:
+-------+------------+-----------+----------+
|Id |DateTime |SensorId |Value |
+-------+------------+-----------+----------+
SensorId is a foreign key to a table of the sensor details. SensorId 是传感器详细信息表的外键。 There will be 10m+ records in this values table.此值表中将有 10m+ 条记录。
I can run this sql command to return the most recent record for each SensorId and it runs in about 0.3 seconds.我可以运行这个 sql 命令来返回每个 SensorId 的最新记录,它运行大约 0.3 秒。
SELECT a.*
FROM Values as a
INNER JOIN (
SELECT SensorId, MAX(ID) maxId
FROM Values
GROUP BY SensorId
) b ON a.SensorId = b.SensorId
AND a.Id = b.maxId
ORDER BY a.SensorId ASC
How can I achieve the same output with entity framework in ac# application while maintaining (or improving) the performance?如何在保持(或提高)性能的同时,在 ac# 应用程序中使用实体框架实现相同的输出?
With LINQ to Entities and lambdas you can do it like this:使用 LINQ to Entities 和 lambdas,您可以这样做:
dataContext.Values.GroupBy(p => p.SensorId)
.Select(p => p.FirstOrDefault(w => w.Id == p.Max(m => m.Id)))
.OrderBy(p => p.SensorId).ToList()
where dataContext is your instance of ObjectContext
class.其中 dataContext 是您的ObjectContext
类的实例。 ToList()
compiles the query. ToList()
编译查询。
context.Values.FromSqlRaw<Values>("SELECT a.*
FROM Values as a
INNER JOIN (
SELECT SensorId, MAX(ID) maxId
FROM Values
GROUP BY SensorId
) b ON a.SensorId = b.SensorId
AND a.Id = b.maxId
ORDER BY a.SensorId ASC").ToList<Values>();
FromSqlRaw is faster than a normal Linq Query. FromSqlRaw 比普通的 Linq 查询更快。 for EF you can try context.ExecuteQuery<Values>
by the same way.对于 EF,您可以通过相同的方式尝试context.ExecuteQuery<Values>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.