EntityFrameworkCore 分页问题

场景重现

使用 EntityFrameworkCore 连接 SQL Server 2008 执行.Skip().Take()分页查询时出现如下异常:

SqlException: 'OFFSET' 附近有语法错误。
在 FETCH 语句中选项 NEXT 的用法无效。

异常原因

SQL Server 中有几种实现分页的方式,但是有版本限制.

  • top not in 方式 - SQL Server 2005 新增的
  • ROW_NUMBER() OVER()方式 - SQL Server 2008 新增的
  • offset fetch next 方式 - SQL Server 2012 新增的

而在EntityFramworkCore中默认使用的是最新的offset fetch方式,
而我使用的 SQL Server 2008 不支持该关键字, 自然就异常.

解决办法

这是 EntityFrameworkCore 中的原话.

Use a ROW_NUMBER() in queries instead of OFFSET/FETCH. This method is backwards-compatible to SQL Server 2005. public virtual void UseRowNumberForPaging();

于是乎,我们指定下 EntityFramworkCore 中使用的分页模式即可.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UserSqlServer("yourConnectionString", options => {
        options.UseRowNumberForPaging();
    });
}
原文地址:https://www.cnblogs.com/taadis/p/12126171.html