.Net EF Core數據庫使用SQL server 2008 R2分頁報錯How to avoid the “Incorrect syntax near 'OFFSET'. Invalid usage of the option NEXT in the FETCH statement.”


一、  問題說明

最近.Net EF core 程序部署到服務器,服務器數據庫安裝的是SQL server 2008 R2,我本地用的的是SQL server 2014,在用到分頁查詢時報錯如下:

How to avoid the “Incorrect syntax near 'OFFSET'. Invalid usage of the option NEXT in the FETCH statement.”

通過問題描述可以分析是數據庫SQL server 2008 R2版本SQL語句不支持關鍵字OFFSET,NEXT,因為這兩個關鍵字是SQL server 2012以后的新特性。

二、  解決方案

由於我采用的是.Net core EF code first訪問數據庫,在網上查找如何制定數據庫版本,沒有太多有用的資料。最后在EntityFrameworkCore官方開源github issue里找到了解決方案,因為已經有人先遇到這個問題了。

Github issue連接地址:https://github.com/aspnet/EntityFrameworkCore/issues/4616

通過配置.UseRowNumberForPaging() 即配置用row number SQL關鍵字進行分頁,詳細代碼如下:

public static class MyDBContextConfigurer
{
        public static void Configure(DbContextOptionsBuilder<MyDBContext> builder, string connectionString)
        {
            builder.UseSqlServer(connectionString, option => option.UseRowNumberForPaging() );
        }

        public static void Configure(DbContextOptionsBuilder<MyDBContext> builder, DbConnection connection)
        {
            builder.UseSqlServer(connection, option => option.UseRowNumberForPaging());
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM