简体   繁体   English

实体框架为每种类型的记录选择最近的记录

[英]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()编译查询。

  1. I guess it would not be possible reach better performance than pure SQl query because by using EF you are adding abstraction layer to the process.我想它不可能达到比纯 SQL 查询更好的性能,因为通过使用 EF,您正在向流程添加抽象层。
  2. EF is usually very slow with GroupBy command.使用 GroupBy 命令时,EF 通常很慢。 I suggest try sql query in EF directly (this code is for EF Core )我建议直接在 EF 中尝试 sql 查询(此代码适用于EF Core
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM