CSharp-Single-EFCore/Bunny.Common/Context/Database/GetPagedResultAsync.cs

28 lines
1.1 KiB
C#

using Bunny.Dao.Common.Result;
using Microsoft.EntityFrameworkCore;
namespace Bunny.Common.Context.Database;
public static class GetPagedResultAsync
{
public static async Task<PageResult<T>> GetPagedListAsync<T>(IQueryable<T> source, int page, int limit)
{
var total = await source.CountAsync();
IEnumerable<T> items = await source.Skip((page - 1) * limit).Take(limit).ToListAsync();
return new PageResult<T>(page, limit, total, items);
}
public static async Task<PageResult<T>> GetPagedListFromSqlAsync<T>(DbContext dbContext, string sql, string table, int page, int limit)
where T : class
{
// 计算SQL查询的总数
var total = await dbContext.Set<T>().CountAsync();
// 执行分页查询
var paginatedSql =
$"{sql} ORDER BY (SELECT NULL) OFFSET {(page - 1) * limit} ROWS FETCH NEXT {limit} ROWS ONLY";
IEnumerable<T> items = await dbContext.Set<T>().FromSqlRaw(paginatedSql).ToListAsync();
return new PageResult<T>(page, limit, total, items);
}
}