How to get the latest row in a table using Entity Framework (considering performance)?

11,299

The Entity Framework generates the following SQL for me:

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.

Therefore, I don't believe there is a better or faster way to do this in 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.

Share:
11,299
GibboK
Author by

GibboK

A professional and enthusiastic Senior Front End Developer. Listed as top 2 users by reputation in Czech Republic on Stack Overflow. Latest open source projects Animatelo - Porting to JavaScript Web Animations API of Animate.css (430+ stars on GitHub) Industrial UI - Simple, modular UI Components for Shop Floor Applications Frontend Boilerplate - An opinionated boilerplate which helps you build fast, robust, and adaptable single-page application in React Keyframes Tool - Command line tool which convert CSS Animations to JavaScript objects gibbok.coding📧gmail.com

Updated on June 24, 2022

Comments

  • GibboK
    GibboK almost 2 years

    I am concerning about performance, specially on large table. In my example StatusId is a 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);
        }
    
  • AcidJunkie
    AcidJunkie about 10 years
    @ken2k Having a look at the actual SQL Execution Plan says otherwise. The main load comes from the index scan.