其他分享
首页 > 其他分享> > dotnetcore EF 分页

dotnetcore EF 分页

作者:互联网

保存100个students,有意思的是虽然看似所有的students应该有序插入,但是db显示students的顺序是乱的。

        // 保存100个students,有意思的是虽然看似所有的students应该有序插入,但是db显示students的顺序是乱的。
        private static async Task SaveStudents(MyDbContext ctx)
        {
            for (int i = 0; i < 100; i++)
            {
                Student student = new Student()
                {
                    Name = $"student_{i}",
                };

                ctx.Students.Add(student);
            }

            await ctx.SaveChangesAsync();
        }

使用skip/take实现分页功能

        // 使用skip/take实现分页功能。
        private static Task GetStudentsPerPage(MyDbContext ctx, int pageSize)
        {
            long count = ctx.Students.LongCount();
            int pageCount = (int)Math.Ceiling(count * 1.0 / pageSize);

            for (int pageNo = 0; pageNo < pageCount; pageNo++)
            {
                Console.WriteLine($"Page #{pageNo}, size {pageSize}");
                foreach (Student s in ctx.Students.Skip(pageNo * pageSize).Take(pageSize))
                {
                    Console.WriteLine("  " + s.Name);
                }
            }

            return Task.CompletedTask;
        }

longcount语句被翻译成了COUNT_BIG

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT_BIG(*)
      FROM [student] AS [s]

skip/take被翻译成offset和fetch。

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[@__p_0='?' (DbType = Int32), @__p_1='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT [s].[Id], [s].[Name]
      FROM [student] AS [s]
      ORDER BY (SELECT 1)
      OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY
  ??
  ??
  ??
  student_0
  student_72
  student_71
  student_70
  student_69
  student_68
  student_67
  student_66
  student_65

标签:分页,pageSize,students,EF,ctx,pageNo,int,dotnetcore,student
来源: https://www.cnblogs.com/mryux/p/15858490.html