LINQ系列:LINQ to SQL Take/Skip

libingql發表於2014-10-26

1. Take

var expr = context.Products
    .Take(10);
var expr = (from p in context.Products
            select p)
            .Take(10);
SELECT TOP (10) 
    [c].[ProductID] AS [ProductID], 
    [c].[CategoryID] AS [CategoryID], 
    [c].[ProductName] AS [ProductName], 
    [c].[UnitPrice] AS [UnitPrice], 
    [c].[UnitsInStock] AS [UnitsInStock], 
    [c].[Discontinued] AS [Discontinued]
    FROM [dbo].[Product] AS [c]

2. Skip

  在使用Skip方法之前,需要先有OrderBy排序。

var expr = context.Products
    .Select(p => new { p.ProductID, p.ProductName })
    .OrderBy(p => p.ProductID)
    .Skip(10);
SELECT 
    [Extent1].[ProductID] AS [ProductID], 
    [Extent1].[ProductName] AS [ProductName]
    FROM ( SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], row_number() OVER (ORDER BY [Extent1].[ProductID] ASC) AS [row_number]
        FROM [dbo].[Product] AS [Extent1]
    )  AS [Extent1]
    WHERE [Extent1].[row_number] > 10
    ORDER BY [Extent1].[ProductID] ASC

3. 分頁查詢Take/Skip

var expr = context.Products
    .Select(p => new { p.ProductID, p.ProductName })
    .OrderBy(p => p.ProductID)
    .Skip(10)
    .Take(10);
SELECT TOP (10) 
    [Extent1].[ProductID] AS [ProductID], 
    [Extent1].[ProductName] AS [ProductName]
    FROM ( SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], row_number() OVER (ORDER BY [Extent1].[ProductID] ASC) AS [row_number]
        FROM [dbo].[Product] AS [Extent1]
    )  AS [Extent1]
    WHERE [Extent1].[row_number] > 10
    ORDER BY [Extent1].[ProductID] ASC

相關文章