using System.Linq.Expressions;
using SqlSugar;
namespace Entity.Base
{
///
/// 分页泛型集合
///
///
public class SqlSugarPagedList
{
///
/// 页码
///
public int Page { get; set; }
///
/// 页容量
///
public int PageSize { get; set; }
///
/// 总条数
///
public int Total { get; set; }
///
/// 总页数
///
public int TotalPages { get; set; }
///
/// 当前页集合
///
public IEnumerable Items { get; set; }
///
/// 是否有上一页
///
public bool HasPrevPage { get; set; }
///
/// 是否有下一页
///
public bool HasNextPage { get; set; }
}
///
/// 分页拓展类
///
public static class SqlSugarPagedExtensions
{
///
/// 分页拓展
///
/// 对象
/// 当前页码,从1开始
/// 页码容量
/// 查询结果 Select 表达式
///
public static SqlSugarPagedList ToPagedList(this ISugarQueryable query,
int pageIndex, int pageSize,
Expression> expression)
{
var total = 0;
var items = query.ToPageList(pageIndex, pageSize, ref total, expression);
return CreateSqlSugarPagedList(items, total, pageIndex, pageSize);
}
///
/// 分页拓展
///
/// 对象
/// 当前页码,从1开始
/// 页码容量
///
public static SqlSugarPagedList ToPagedList(this ISugarQueryable query,
int pageIndex, int pageSize)
{
var total = 0;
var items = query.ToPageList(pageIndex, pageSize, ref total);
return CreateSqlSugarPagedList(items, total, pageIndex, pageSize);
}
///
/// 分页拓展
///
/// 对象
/// 当前页码,从1开始
/// 页码容量
/// 查询结果 Select 表达式
///
public static async Task> ToPagedListAsync(
this ISugarQueryable query, int pageIndex, int pageSize,
Expression> expression)
{
RefAsync total = 0;
var items = await query.ToPageListAsync(pageIndex, pageSize, total, expression);
return CreateSqlSugarPagedList(items, total, pageIndex, pageSize);
}
///
/// 分页拓展
///
/// 对象
/// 当前页码,从1开始
/// 页码容量
///
public static async Task> ToPagedListAsync(
this ISugarQueryable query, int pageIndex, int pageSize)
{
RefAsync total = 0;
var items = await query.ToPageListAsync(pageIndex, pageSize, total);
return CreateSqlSugarPagedList(items, total, pageIndex, pageSize);
}
///
/// 分页拓展
///
/// 集合对象
/// 当前页码,从1开始
/// 页码容量
///
public static SqlSugarPagedList ToPagedList(this IEnumerable list, int pageIndex,
int pageSize)
{
var total = list.Count();
var items = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return CreateSqlSugarPagedList(items, total, pageIndex, pageSize);
}
///
/// 创建 对象
///
///
/// 分页内容的对象集合
/// 总条数
/// 当前页码,从1开始
/// 页码容量
///
public static SqlSugarPagedList CreateSqlSugarPagedList(IEnumerable items, int total,
int pageIndex, int pageSize)
{
var totalPages = pageSize > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;
return new SqlSugarPagedList
{
Page = pageIndex,
PageSize = pageSize,
Items = items,
Total = total,
TotalPages = totalPages,
HasNextPage = pageIndex < totalPages,
HasPrevPage = pageIndex - 1 > 0
};
}
}
}