EF框架 与 Dapper框架 调用分页存储过程

1. SqlServer创建存储过程:

--创建存储过程
create proc sp_Show
(
    @index int,  --当前页
    @size int,     --每页大小
    @totalcount int out,  --总数据数
    @pagecount int out      --总页数
)
as
begin 
    --计算总数据数
    select @totalcount=COUNT(*) from Goods       --(where name like '%'+ @name +'%')
    --计算总页数
    set @pagecount=CEILING(@totalcount*1.0/@size)

    if(@index<=0)
    set @index=1
    if(@index>=@pagecount)
    set @index=@pagecount

    --分页查询
    select * from 
        (select ROW_NUMBER() over(order by GId) rn,*from Goods) tb1 where    --(where name like '%'+ @name +'%')
        rn between ((@index-1)*@size)+1 and (@index*@size)
end

declare @x int,@y int
exec sp_Show 1,2,@x out,@y out
select @x 总数据数,@y 总页数

2.  Entity FrameWork框架:

      //分页存储过程显示
        [HttpGet]
        public PageDate GetGoods2(int index, int size)
        {
            //实例化参数
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@index",index),
                new SqlParameter("@size",size),
                new SqlParameter("@totalcount",SqlDbType.Int), //总数据数
                new SqlParameter("@pagecount",SqlDbType.Int),  //总页数
            };
            //指定输出参数
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;

            //存储过程查询
            var list = db.Database.SqlQuery<Goods>("exec sp_Show @index,@size,@totalcount out,@pagecount out", parameters).ToList();

            PageDate page = new PageDate();
            page.List = list;
            page.PageCount = int.Parse(parameters[3].Value.ToString());
            return page;
        }

3. Dapper框架:

     //存储过程分页
        [HttpGet]
        public PageDate GetGoods2(int index, int size)
        {
          //添加参数
            var p = new DynamicParameters();
            p.Add("@index", index);
            p.Add("@size", size);
          //指定输出参数
            p.Add("@totalcount", dbType: DbType.Int32, direction: ParameterDirection.Output);  //总数据数
            p.Add("@pagecount", dbType:DbType.Int32,direction:ParameterDirection.Output);      //总页数

            List<Goods> list = new List<Goods>();
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                list = conn.Query<Goods>("sp_Show",p,commandType:CommandType.StoredProcedure).ToList();
            }

            PageDate page = new PageDate();
            page.List = list;
           //获取指定的参数值
            page.PageCount = p.Get<int>("@pagecount");
            return page;
        }
原文地址:https://www.cnblogs.com/igqx/p/13445360.html