Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

c# - Why does System.Data.Linq generates ROW_NUMBER() for Paging instead of OFFSET/FETCH for SQL Server 2012

We are using Linq and Entity Framework to access a SQL Server 2012 database. We are having some performance issue, so after some investigation, we were able to fix some of the problems, but I would like to use SQL query with OFFSET/FETCH instead of ROW_NUMBER() and BETWEEN syntax.

The performance difference is not so big. OFFSET/FETCH is quicker by about 10%. Do you have any idea why the generated query uses ROW_NUMBER() and BETWEEN syntax? What can I do to force Linq to generate OFFSET/FETCH query?

C# code:

var orders = dc.Orders.OrderBy(q => q.LastModifiedTimestamp)
                      .Skip(q => skipCount)
                      .Take(q => takeCount)
                      .ToList();

The currently generated query:

-- Region Parameters
DECLARE @p0 Int = 10
DECLARE @p1 Int = 10
-- EndRegion
SELECT [t2].[OrderId], [t2].[CustomerId]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [t1].[OrderId], [t1].[CustomerId]
    FROM (
        SELECT DISTINCT [t0].[OrderId], [t0].[CustomerId]
        FROM [Order] AS [t0]
        ) AS [t1]
    ) AS [t2]
WHERE [t2].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t2].[ROW_NUMBER]

The preferred query:

SELECT *
FROM [Order]
ORDER BY LastModifiedTimestamp
    OFFSET 10000 ROWS
    FETCH NEXT 10000 ROWS ONLY

Do you have any idea why the generated query use ROW_NUMBER() and BETWEEN syntax? What can I do to force Linq to generate OFFSET/FETCH query?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...