Entity Framework 分页处理

在SQL中进行分页,网上已经有很多例子了,在这里我使用Linq to SQL让C#来生成分页代码,首先创建分页的扩展方法:

  
    public static class Extensions
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list"> 数据源 </param>
        /// <param name="order"> 排序表达式 </param>
        /// <param name="page"> 第几页 </param>
        /// <param name="size"> 每页记录数 </param>
        /// <param name="count"> 记录总数 </param>
        /// <returns></returns>
        public static IQueryable<T> Pagination<T,TKey>(this IQueryable<T> list, Expression<Func<T, TKey>> order, int page, int size, out int count)
        {
            count = list.Count();
            return list.Distinct().OrderBy(order).Skip((page - 1) * size).Take(size);
        }
    }

 

然后在程序中调用起来也很方便(只需要在linq查询中直接调用扩展方法即可):
                int count;
                var q = (from in context.WT_Tickets
                    join b in context.WT_OrderForm on a.OrderId equals b.Id
                    select new
                    {
                        BusNo = a.BusNumber,
                        OrderId = b.Id,
                        OrderDate = b.OrderDateTime,
                    }).Where(t=>t.OrderId.Length > 5).Distinct().Pagination(1, 10, out count);
                var data = q.ToList();
 
另外一种分页方式,按偏移量和页面记录数来获取数据:
    public static class Extensions
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list">数据源</param>
        /// <param name="offset">偏移量</param>
        /// <param name="limit">查询记录数</param>
        /// <param name="count">记录总数</param>
        /// <returns></returns>
        public static IQueryable<T> Pagination<T>(this IQueryable<T> list,int offset,int limit,out int count)
        {
            count = list.Count();
            return list.OrderBy(t => t).Skip(offset).Take(limit);
        }
    }
View Code

 

posted @ 2015-02-11 14:01  ChirsLee  阅读(5070)  评论(0编辑  收藏  举报