/// <summary> /// 异步从 <see cref="IDbQueryable{TSource}"/> 创建分页记录 <see cref="PagedList{TSource}"/> /// </summary> /// <typeparam name="TSource">返回类型</typeparam> /// <param name="source">查询序列</param> /// <param name="pageIndex">当前页</param> /// <param name="pageSize">页长,1024表示取所有记录</param> /// <returns></returns> public static async Task <PagedList <TSource> > ToPagedListAsync <TSource>(this IDbQueryable <TSource> source, int pageIndex, int pageSize = 10) { IList <TSource> result = null; int rowCount = 0; int pages = 0; if (pageSize == 1024) { result = await source.ToListAsync(); rowCount = result.Count; pageIndex = 1; pages = 1; } else { if (pageSize == 0) { pageSize = 10; } rowCount = await source.CountAsync(); if (rowCount == 0) { result = new List <TSource>(0); } else { pages = rowCount / pageSize; if (rowCount % pageSize > 0) { ++pages; } if (pageIndex > pages) { pageIndex = pages; } if (pageIndex < 1) { pageIndex = 1; } result = await source.ToListAsync(pageIndex, pageSize); } } return(new PagedList <TSource>(result, pageIndex, pageSize, rowCount)); }
/// <summary> /// 异步从 <see cref="IDbQueryable<TElement>"/> 创建 <see cref="PagedList<TElement>"/> /// pageSize = 1024 表示取所有 /// </summary> public static async Task <PagedList <TElement> > ToPagedListAsync <TElement>(this IDbQueryable <TElement> source, int pageIndex, int pageSize = 10) { IList <TElement> result = null; int totalCount = 0; int totalPages = 0; if (pageSize == 1024) { result = await source.ToListAsync(); totalCount = result.Count; pageIndex = 1; totalPages = 1; } else { if (pageSize == 0) { pageSize = 10; } totalCount = await source.CountAsync(); totalPages = totalCount / pageSize; if (totalCount % pageSize > 0) { ++totalPages; } if (pageIndex > totalPages) { pageIndex = totalPages; } if (pageIndex < 1) { pageIndex = 1; } result = await source.ToListAsync(pageIndex, pageSize); } return(new PagedList <TElement>(result, pageIndex, pageSize, totalCount)); }
/// <summary> /// 返回序列中的元素数量 /// </summary> public static async Task <int> CountAsync <TSource>(this IDbQueryable <TSource> source) { int num = await source.CountAsync(null); return(num); }