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

 

posted @ 2018-03-24 13:48  DonaldTDZ  阅读(3604)  评论(1编辑  收藏  举报