🚀 feat(新增): 分页查询有问题

This commit is contained in:
Bunny 2024-09-12 23:05:46 +08:00
parent c097849f63
commit ce8c83b7a8
14 changed files with 68 additions and 50 deletions

View File

@ -1,23 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="bunny" uuid="b6cf8a1e-027c-4a20-8eff-d18024c58281">
<driver-ref>sqlite.xerial</driver-ref>
<data-source source="LOCAL" name="BunnyDemo@192.168.3.98" uuid="9bd9e2e8-592a-460b-9e5f-67a43c07ca12">
<driver-ref>sqlserver.jb</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:D:\Project\web\Bunny-Cli\template\CSharp\CSharp-Single-EFCore\Bunny.WebApi\Database\bunny.db</jdbc-url>
<jdbc-driver>com.jetbrains.jdbc.sqlserver.SqlServerDriver</jdbc-driver>
<jdbc-url>Server=192.168.3.98;Database=BunnyDemo</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.resource.type" value="Deployment" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
<libraries>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/xerial/sqlite-jdbc/3.45.1.0/sqlite-jdbc-3.45.1.0.jar</url>
</library>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar</url>
</library>
</libraries>
</data-source>
</component>
</project>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/Bunny.Service/IService/Service/UserService.cs" dialect="TSQL" />
<file url="PROJECT" dialect="TSQL" />
</component>
</project>

View File

@ -22,6 +22,7 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Minio" Version="6.0.3"/>
<PackageReference Include="morelinq" Version="4.3.0"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3"/>
<PackageReference Include="StackExchange.Redis" Version="2.8.0"/>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.6.0"/>

View File

@ -5,6 +5,7 @@ using Bunny.Dao.Entity.System.Menu;
using Bunny.Dao.Entity.System.User;
using log4net;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
namespace Bunny.Common.Context.Database;
@ -22,8 +23,6 @@ public class EfCoreContext : DbContext
public EfCoreContext()
{
var dataBaseConnection = AppSettings.GetAppConfig<string>("DataBase:DataBaseConnection");
// const string dataBaseConnection =
// "192.168.3.98;Initial Catalog=BunnyDemo;TrustServerCertificate=True;Persist Security Info=True;Users ID=sa;Password=abc1234.";
DbPath = $"Data Source={dataBaseConnection}";
}
@ -46,7 +45,9 @@ public class EfCoreContext : DbContext
/// </summary>
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
Log.Info("正在连接数据库。。。");
options.UseSqlServer(DbPath);
Log.Info("连接数据库完成层。。。");
}
/// <summary>
@ -55,7 +56,7 @@ public class EfCoreContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 为每个表指定 blogging 架构
modelBuilder.HasDefaultSchema("blogging");
modelBuilder.HasDefaultSchema("dbo");
// 根据基础类型创建数据库表
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
@ -116,7 +117,7 @@ public class EfCoreContext : DbContext
// 添加操作
case EntityState.Added:
{
if (entity.Id == Guid.Empty) entity.Id = Guid.NewGuid();
if (entity.Id.IsNullOrEmpty()) entity.Id = Guid.NewGuid().ToString();
entity.CreateTime = DateTime.Now;
entity.UpdateTime = DateTime.Now;
entity.Version = DateTime.Now;

View File

@ -0,0 +1,28 @@
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);
}
}

View File

@ -1,29 +1,29 @@
namespace Bunny.Dao.Common.Result;
public class PageResult<T>
public class PageResult<T>(int page, int limit, int total, IEnumerable<T> data)
{
/// <summary>
/// 当前页
/// </summary>
public int PageNo { get; set; }
public int Page { get; set; } = page;
/// <summary>
/// 页容量
/// </summary>
public int PageSize { get; set; }
public int Limit { get; set; } = limit;
/// <summary>
/// 总页数
/// </summary>
public int Pages { get; set; }
public int Pages { get; set; } = (int)Math.Ceiling(total / (double)limit);
/// <summary>
/// 总条数
/// </summary>
public int Total { get; set; }
public int Total { get; set; } = total;
/// <summary>
/// 数据
/// </summary>
public List<T>? Data { get; set; }
public IEnumerable<T>? Data { get; set; } = data;
}

View File

@ -9,7 +9,7 @@ public class BaseEntity
[Comment("主键")]
[Column(Order = 0)]
[Key]
public Guid? Id { get; set; }
public string? Id { get; set; }
[Comment("创建时间")] public DateTime CreateTime { get; set; }

View File

@ -4,7 +4,7 @@ using Microsoft.EntityFrameworkCore;
namespace Bunny.Dao.Entity.System.User;
[Table("System_Users", Schema = "blogging")]
[Table("System_Users")]
[Comment("系统用户表")]
public class Users : BaseEntity
{

View File

@ -51,5 +51,5 @@ public interface IUserService
/// </summary>
/// <param name="page"></param>
/// <param name="limit"></param>
PageResult<Users> QueryPage(int page, int limit);
Task<PageResult<Users>> QueryPage(int page, int limit);
}

View File

@ -60,7 +60,7 @@ public class RedisOptionService : IRedisOptionService
{
var post = new Users
{
Id = Guid.NewGuid(),
Id = Guid.NewGuid().ToString(),
Username = "存入JSON内容",
Password = "正在存入JSON内容"
};

View File

@ -1,5 +1,4 @@
using Bunny.Common.Attribute;
using Bunny.Common.Context.Database;
using Bunny.Common.Context.Database;
using Bunny.Common.Exception;
using Bunny.Common.Utils.Net;
using Bunny.Dao.Common.Result;
@ -52,7 +51,7 @@ public class UserService : IUserService
/// <param name="id"></param>
public void DeleteBlog(string id)
{
var blog = new Users { Id = Guid.NewGuid() };
var blog = new Users { Id = Guid.NewGuid().ToString() };
DbContext.Users.Remove(blog);
DbContext.SaveChanges();
}
@ -118,21 +117,9 @@ public class UserService : IUserService
/// </summary>
/// <param name="page"></param>
/// <param name="limit"></param>
[Cacheable("UserService::Get", "00:00:59")]
public PageResult<Users> QueryPage(int page, int limit)
public Task<PageResult<Users>> QueryPage(int page, int limit)
{
var items = DbContext.Users.Take(limit).Skip(page).ToList();
var total = items.Count;
var pages = (int)Math.Ceiling(total / (double)limit);
var blogs = items.Skip((page - 1) * limit).Take(limit).ToList();
return new PageResult<Users>
{
PageNo = page,
Total = total,
PageSize = limit,
Pages = pages,
Data = blogs
};
var pagedListAsync = GetPagedResultAsync.GetPagedListFromSqlAsync<Users>(DbContext, "select * from System_Users ", "System_Users", page, limit);
return pagedListAsync;
}
}

View File

@ -11,7 +11,7 @@ public static class AddAutofacConfig
public static void BuildContainer(ContainerBuilder builder)
{
// 异步方式创建数据库
new EfCoreContext().Database.EnsureCreatedAsync();
new EfCoreContext().Database.EnsureCreated();
// 如果不在在 Controller 层写构造函数可以打开这个,自动完成注入
var controllerBaseType = typeof(ControllerBase);

View File

@ -38,7 +38,7 @@ public class BaseConfig(WebApplicationBuilder builder)
// 让控制器实例由容器创建
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
// 添加定时任务
builder.AddApplicationBackendServices();
// builder.AddApplicationBackendServices();
// 设置过滤器
builder.AddFilterConfigInitialize();
// 初始化Redis

View File

@ -12,7 +12,7 @@ namespace Bunny.WebApi.Controllers;
/// BLog相关接口
/// </summary>
[Microsoft.AspNetCore.Mvc.Route("/api/[controller]/[action]")]
public class BlogController : ControllerBase
public class UserController : ControllerBase
{
[Inject] public required IUserService UserService { get; set; }
@ -101,10 +101,9 @@ public class BlogController : ControllerBase
/// </summary>
/// <returns></returns>
[HttpPost]
public Result<PageResult<Users>> QueryPage(int page = 1, int limit = 10)
public async Task<Result<PageResult<Users>>> QueryPage(int page = 1, int limit = 10)
{
var vo = UserService.QueryPage(page, limit);
var vo = await UserService.QueryPage(page, limit);
return Result<PageResult<Users>>.Success(vo);
}
}