一、 問題說明
最近.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()); }
}