一年半没有做过MVC的项目了,还是很怀念(因为现在项目还是原来的ASPX),个人还是喜欢mvc,最近又开始重拾MVC,感觉既熟悉又陌生。
记录一下封装好的分页代码
public static List<T> SelectPageList<T>(DbSet<T> source, string sqlstr, int pageIndex, int pagesize, string orderByField, ref int totalCount) where T : class { SqlParameter[] spm = new SqlParameter[5]; spm[0] = new SqlParameter("@Sql", sqlstr); spm[1] = new SqlParameter("@PageIndex", pageIndex); spm[2] = new SqlParameter("@PageSize", pagesize); spm[3] = new SqlParameter("@OrderByField", orderByField); spm[4] = new SqlParameter("@TotalRecord", totalCount); spm[4].Direction = ParameterDirection.Output; var data = source.SqlQuery("exec Pro_PageProcedure @Sql,@PageIndex,@PageSize,@OrderByField,@TotalRecord out", spm).ToList(); totalCount = Convert.ToInt32(spm[4].Value.ToString()); return data; }
因为直接用linq的分页方式感觉效率还是不是很高,所以改用存储过程,上面方法用泛型的方式,可以灵活的调用。存储过程网上很多,也可以自己写一个,以下是我用的存储过程
CREATE PROCEDURE [dbo].[Pro_PageProcedure] @Sql nvarchar(max), --表名 @PageIndex int = 1 , --指定当前为第几页 @PageSize int, --每页多少条记录 @OrderByField nvarchar(1000), --row_number需要的排序字段 @TotalRecord int output --返回总页数 as Declare @_sql nvarchar(max); --计算总记录数 set @_sql = ‘select @TotalRecord = count(*) from (‘ + @Sql + ‘) a‘ EXEC sp_executesql @_sql,N‘@TotalRecord int OUTPUT‘,@TotalRecord OUTPUT--计算总记录数 Declare @StartRecord int Declare @EndRecord int set @StartRecord = (@pageIndex-1)*@PageSize + 1 set @EndRecord = @StartRecord + @pageSize - 1 set @_sql =‘select * from ( select ROW_NUMBER() Over(‘ + @OrderByField + ‘) as _ttRowId,* from (‘ + @Sql + ‘) _tt0 ) _tt1 ‘ set @_sql = @_sql + ‘where _ttRowId between ‘ + CAST(@StartRecord as nvarchar) + ‘ and ‘ + CAST(@EndRecord as nvarchar) Exec(@_sql)
上面方法写在基类,各个子类继承基类都可以直接调用此方法进行分页查询,以下是其中一个子类调用
/// <summary> /// 获取分页列表 /// </summary> /// <returns></returns> public List<FixedAnswer> GetPageList(int pageIndex, int pageSize, ref int totalCount) { string strSql = "select * from FixedAnswer"; string orderfied = "order by id desc"; return SelectPageList<FixedAnswer>(db.FixedAnswer, strSql, pageIndex, pageSize, orderfied, ref totalCount); }
时间: 2024-10-26 12:53:45