.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.”

匿名 (未验证) 提交于 2019-12-02 22:10:10

最近.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());         }}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!