Does this linq-to-sql query retrieve all records and then pick one, or retrieve just one?

StackOverflow https://stackoverflow.com/questions/23541443

  •  18-07-2023
  •  | 
  •  

Вопрос

I'm looking for the highest key in a table with a quite a lot of records, and I'm wondering if LINQ to SQL does this efficiently, or if I need to take another approach to make sure the code isn't pulling across all of the records from the database.

        int tkey =
            (from r in GMSCore.db.Receipts
             orderby r.TransactionKey descending
             select r.TransactionKey).FirstOrDefault();

Is this interpreted like:

select Top(1) TransactionKey 
from Receipt
order by TransactionKey desc

Or does it pull all of the records and then filter in the C# code?

Это было полезно?

Решение

It retrieves just one record. Generated query will look like:

SELECT TOP(1) [t0].[TransactionKey] 
FROM Receipt [t0]
ORDER BY [t0].[TransactionKey] DESC

Query is not executed until you call FirstOrDefault() or other operator which forces execution (see Classification of Standard Query Operators by Manner of Execution).

You even can save query definition into variable (feel the difference - not result of query execution, but query itself)

var query = from r in GMSCore.db.Receipts
            orderby r.TransactionKey descending
            select r.TransactionKey;

// Nothing is executed yet
int tkey = query.FirstOrDefault(); // SQL query is generated and executed

You can execute original query later

foreach(var key in query) // another SQL is generated and executed
    // ...

But in this case generated SQL query will look like

SELECT [t0].[TransactionKey] 
FROM Receipt [t0]
ORDER BY [t0].[TransactionKey] DESC

So, you can modify query definition until it is executed. E.g. you can add filtering, or change ordering. In fact operator which executes query also usually affects query generation - e.g. selecting first, single or max item.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top