0
Data = _db.ALLOCATION_D.OrderBy(a => a.ALLO_ID)
                       .Skip(10)
                       .Take(10)
                       .ToList();

Let say I have 100000 rows in ALLOCATION_D table. I want to select first 10 row. Now I want to know how the above statement executes. I don't know but I think it executes in the following way...

  1. first it select the 100000 rows
  2. then ordered by ALLO_ID
  3. then Skip 10
  4. finally select the 10 rows.

Is it right? I want to know more details.

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
Atish Kumar Dipongkor
  • 10,220
  • 9
  • 49
  • 77

3 Answers3

2

This Linq produce a SQL query via Entity Framework. Then it depends on your DBMS, but for SQL Server 2008, here is the query produces:

SELECT TOP (10) [Extent1].[ALLO_ID] AS [ALLO_ID],   
FROM ( 
    SELECT [Extent1].[ALLO_ID] AS [ALLO_ID]
         , row_number() OVER (ORDER BY [Extent1].[ALLO_ID] ASC) AS [row_number]
    FROM [dbo].[ALLOCATION_D] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[row_number] > 10
ORDER BY [Extent1].[ALLO_ID] ASC

You can run this in your C# for retrieve the query:

var linqQuery = _db.ALLOCATION_D
                   .OrderBy(a => a.ALLO_ID)
                   .Skip(10)
                   .Take(10);
var sqlQuery = ((System.Data.Objects.ObjectQuery)linqQuery).ToTraceString();
Data = linqQuery.ToList();

Second option with Linq To SQL

var linqQuery = _db.ALLOCATION_D
                   .OrderBy(a => a.ALLO_ID)
                   .Skip(10)
                   .Take(10);
var sqlQuery = _db.GetCommand(linqQuery).CommandText;
Data = linqQuery.ToList();

References:

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
0

Your statement reads as follows:

  1. Select all rows (overwritten by skip/take)
  2. Order by Allo_ID
  3. Order by Allo_ID again
  4. Skip first 10 rows
  5. Take next 10 rows

If you want it to select the first ten rows, you simply do this:

 Data = _db.ALLOCATION_D // You don't need to order twice
                    .OrderBy(a => a.ALLO_ID)
                    .Take(10)
                    .ToList()
Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
0

Up to the ToList call, the calls only generates expressions. That means that the OrderBy, Skip and Take calls are bundled up as an expression that is then sent to the entity framework to be executed in the database.

Entity framework will make an SQL query from that expression, which returns the ten rows from the table, which the ToList methods reads and places in a List<T> where T is the type of the items in the ALLOCATION_D collection.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005