本内容代码段抄自传智视频
/// <summary> /// 数据库分页 /// </summary> static List<dynamic> GetPageList<T, TKey>(Expression<Func<T, dynamic>> select, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, int pageSize, int pageIndex, out int total, bool isAsc) where T : class { StudyDBEntities context = new StudyDBEntities(); total = context.Set<T>().Where(whereLambda).Count(); var result = context.Set<T>().Where(whereLambda); if (isAsc) result = result.OrderBy(orderLambda); else result = result.OrderByDescending(orderLambda); return result.Skip(pageSize * (pageIndex - 1)).Take(pageSize).Select(select).ToList(); }
其中 total 返回符合条件的总行数
result 返回符合条件的数据
使用:
int total = 0; var list = GetPageList<Student, int>(o => o, o => o.ID > 2, o => o.ID, 5, 5, out total, true);
ViewData.Model = 实体 .OrderBy(u => u.UserId) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize) .AsEnumerable();
SQL 生成如下:
SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[Student] AS [Extent1] WHERE [Extent1].[ID] > 2 ) AS [GroupBy1]
SELECT TOP (5) [Filter1].[ID] AS [ID], [Filter1].[Name] AS [Name], [Filter1].[Class] AS [Class] FROM ( SELECT [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Class] AS [Class], row_number() OVER (ORDER BY [Extent1].[ID] ASC) AS [row_number] FROM [dbo].[Student] AS [Extent1] WHERE [Extent1].[ID] > 2 ) AS [Filter1] WHERE [Filter1].[row_number] > 20 ORDER BY [Filter1].[ID] ASC