LINQ系列:LINQ to SQL Take/Skip

时间:2022-02-22 04:58:08

1. Take

var expr = context.Products
.Take();
var expr = (from p in context.Products
select p)
.Take();
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();
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()
.Take();
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