I am concerning about performance, specially on large table. In my example StatusId is a IDENTIY PRIMARY KEY
.
我很关心性能,特别是在大桌子上。在我的例子中,StatusId是一个IDENTIY PRIMARY KEY。
I would like to know if there is a better way (faster) to get the last entry in a table.
我想知道是否有更好的方法(更快)来获取表中的最后一个条目。
public IQueryable<GaStatus> GetLastStatus()
{
return context.GaStatuses.OrderByDescending(x => x.StatusId).Take(1);
}
2 个解决方案
#1
5
The Entity Framework generates the following SQL for me:
实体框架为我生成以下SQL:
SELECT TOP (1)
[Extent1].[StatusId] AS [StatusId]
FROM [dbo].[GaStatuses] AS [Extent1]
ORDER BY [Extent1].[StatusId] DESC
This looks like a reasonable way to get the desired result, although 'Extent1' is not easy to read. See for example How to read the last row with SQL Server.
这看起来是获得所需结果的合理方法,尽管“Extent1”不易阅读。请参阅示例如何使用SQL Server读取最后一行。
Therefore, I don't believe there is a better or faster way to do this in Entity Framework.
因此,我不相信在Entity Framework中有更好或更快的方法。
But there is almost always a way to improve the performance of a given SQL query. For example, looking at the execution plan in my particular database, the ORDER BY does a clustered index scan. This might or might not be good from a performance point of view. So, depending on your database, you might be able to identify performance problems and improve performance by writing the SQL directly rather than having Entity Framework generate it for you.
但是几乎总有一种方法可以改善给定SQL查询的性能。例如,查看特定数据库中的执行计划,ORDER BY执行聚簇索引扫描。从性能的角度来看,这可能会或可能不会很好。因此,根据您的数据库,您可以通过直接编写SQL来识别性能问题并提高性能,而不是让Entity Framework为您生成它。
#2
-2
return context.GaStatuses.Max(x => x.StatusId);
return context.GaStatuses.Max(x => x.StatusId);
#1
5
The Entity Framework generates the following SQL for me:
实体框架为我生成以下SQL:
SELECT TOP (1)
[Extent1].[StatusId] AS [StatusId]
FROM [dbo].[GaStatuses] AS [Extent1]
ORDER BY [Extent1].[StatusId] DESC
This looks like a reasonable way to get the desired result, although 'Extent1' is not easy to read. See for example How to read the last row with SQL Server.
这看起来是获得所需结果的合理方法,尽管“Extent1”不易阅读。请参阅示例如何使用SQL Server读取最后一行。
Therefore, I don't believe there is a better or faster way to do this in Entity Framework.
因此,我不相信在Entity Framework中有更好或更快的方法。
But there is almost always a way to improve the performance of a given SQL query. For example, looking at the execution plan in my particular database, the ORDER BY does a clustered index scan. This might or might not be good from a performance point of view. So, depending on your database, you might be able to identify performance problems and improve performance by writing the SQL directly rather than having Entity Framework generate it for you.
但是几乎总有一种方法可以改善给定SQL查询的性能。例如,查看特定数据库中的执行计划,ORDER BY执行聚簇索引扫描。从性能的角度来看,这可能会或可能不会很好。因此,根据您的数据库,您可以通过直接编写SQL来识别性能问题并提高性能,而不是让Entity Framework为您生成它。
#2
-2
return context.GaStatuses.Max(x => x.StatusId);
return context.GaStatuses.Max(x => x.StatusId);