refactor: 重构项目基础架构与实体体系

- 替换原有自定义生命周期接口为通用基础服务体系
- 将所有实体基类替换为带雪花ID的SqlSugarBaseEntity
- 迁移DTO到Models项目并统一管理
- 移除冗余的Repository层实现,改用通用基础服务
- 添加Yitter.IdGenerator雪花ID生成支持
- 重构SqlSugar数据库上下文与依赖注入配置
- 新增微信用户、用户勋章、背包等实体与配套服务
- 整理分页查询与结果封装类
- 优化WebApi控制器结构
This commit is contained in:
glz
2026-06-02 14:10:43 +08:00
parent 831f8ba7f5
commit 8ed012bba8
51 changed files with 1762 additions and 1141 deletions

View File

@ -1,154 +1,293 @@
using Mapster;
using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.Infrastructure.Context;
using QYZH.InteractiveMagazine.Models.Dto;
using SqlSugar;
using SqlSugar.IOC;
using System.Data;
using System.Linq.Expressions;
namespace QYZH.InteractiveMagazine.Repository;
/// <summary>
/// 基础仓储实现
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
namespace QYZH.InteractiveMagazine.Repository
{
/// <summary>
/// SqlSugar 数据库实例
/// 数据仓库类
/// </summary>
protected SqlSugarClient Db => SqlSugarDbContext.GetDb();
/// <summary>
/// 根据Id获取实体自动过滤已删除数据
/// </summary>
/// <param name="id">主键Id</param>
/// <returns>实体对象</returns>
public async Task<T?> GetByIdAsync(long id)
/// <typeparam name="T"></typeparam>
public class BaseRepository<T> : SimpleClient<T> where T : class, new()
{
return await Db.Queryable<T>().In(id).FirstAsync();
}
/// <summary>
/// 获取所有列表(自动过滤已删除数据)
/// </summary>
/// <returns>实体列表</returns>
public async Task<List<T>> GetListAsync()
{
return await Db.Queryable<T>().ToListAsync();
}
/// <summary>
/// 根据条件获取列表(自动过滤已删除数据)
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>实体列表</returns>
public async Task<List<T>> GetListByWhereAsync(Expression<Func<T, bool>> where)
{
return await Db.Queryable<T>().Where(where).ToListAsync();
}
/// <summary>
/// 分页查询(自动过滤已删除数据)
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="pageQuery">分页参数</param>
/// <returns>分页结果</returns>
public async Task<PageListModel<T>> GetPageListAsync(Expression<Func<T, bool>> where, PageQueryModel pageQuery)
{
RefAsync<int> total = 0;
var query = Db.Queryable<T>().Where(where);
// 处理排序
if (!string.IsNullOrEmpty(pageQuery.SortField))
private readonly ILogger<BaseRepository<T>> _logger;
public BaseRepository(ISqlSugarClient context = null) : base(context)
{
var isAsc = string.IsNullOrEmpty(pageQuery.SortOrder) ||
pageQuery.SortOrder.ToLower() == "asc";
query = isAsc
? query.OrderBy($"{pageQuery.SortField} asc")
: query.OrderBy($"{pageQuery.SortField} desc");
Context = DbScoped.SugarScope;
_logger = ServiceContext.GetService<ILogger<BaseRepository<T>>>();
}
var list = await query.ToPageListAsync(pageQuery.PageIndex, pageQuery.PageSize, total);
#region add
return new PageListModel<T>
public IInsertable<T> Insertable(T t)
{
PageIndex = pageQuery.PageIndex,
PageSize = pageQuery.PageSize,
TotalCount = total,
List = list
};
return Context.Insertable(t);
}
#endregion add
#region update
public IUpdateable<T> Updateable(T t)
{
return Context.Updateable(t);
}
public IUpdateable<T> Updateable()
{
return Context.Updateable<T>();
}
public IUpdateable<T1> Updateable<T1>() where T1 : class, new()
{
return Context.Updateable<T1>();
}
/// <summary>
/// 根据指定条件更新指定列 egUpdate(new SysUser(){ Status = 1 }, it => new { it.Status }, f => f.Userid == 1));
/// 只更新Status列条件是包含
/// </summary>
/// <param name="entity">实体类</param>
/// <param name="expression">要更新列的表达式</param>
/// <param name="where">where表达式</param>
/// <returns></returns>
public async Task<bool> UpdateAsync(Expression<Func<T, bool>> columns, Expression<Func<T, bool>> where)
{
return await Context.Updateable<T>().SetColumns(columns).Where(where).ExecuteCommandAsync() > 0;
}
#endregion update
/// <summary>
/// 事务 异步 无返回值
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public async Task UseTranAsync(Func<Task> action)
{
Context.Ado.BeginTran();//using不能少
try
{
await action();
Context.Ado.CommitTran();
}
catch (Exception ex)
{
Context.Ado.RollbackTran();
_logger.LogError($"UseTran 异常:{ex.StackTrace}{ex.Message}");
throw;
}
}
/// <summary>
/// 事务 异步 返回bool
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public async Task<bool> UseTranAsync(Func<Task<bool>> action)
{
Context.Ado.BeginTran();//using不能少
try
{
var result = await action();
if (result)
{
Context.Ado.CommitTran();
return true;
}
else
{
Context.Ado.RollbackTran();
return false;
}
}
catch (Exception ex)
{
Context.Ado.RollbackTran();
_logger.LogError($"UseTran 异常:{ex.StackTrace}{ex.Message}");
throw;
}
}
#region delete
public IDeleteable<T> Deleteable()
{
return Context.Deleteable<T>();
}
#endregion delete
#region query
public bool Any(Expression<Func<T, bool>> expression)
{
return Context.Queryable<T>().Any(expression);
}
public ISugarQueryable<T> Queryable()
{
return Context.Queryable<T>();
}
public ISugarQueryable<T1> Queryable<T1>()
{
return Context.Queryable<T1>();
}
/// <summary>
/// 根据条件表达式查询单条数据
/// </summary>
/// <param name="expression">表达式</param>
/// <returns>泛型实体</returns>
public Task<R> GetByIdAsync<R>(Expression<Func<T, bool>> expression) where R : class
{
return Context.Queryable<T>().Where(expression).Select<R>().FirstAsync();
}
public Task<R> GetByExpressionAsync<R>(Expression<Func<T, bool>> expression) where R : class
{
return Context.Queryable<T>().Where(expression).Select<R>().FirstAsync();
}
public Task<List<T2>> GetListByExpression<T2>(Expression<Func<T, bool>> expression) where T2 : class
{
return Context.Queryable<T>().Where(expression).Select<T2>().ToListAsync();
}
/// <summary>
/// 根据条件查询分页数据
/// </summary>
/// <param name="where"></param>
/// <param name="parm"></param>
/// <returns></returns>
public PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm)
{
var source = Context.Queryable<T>().Where(where);
return source.ToPage(parm);
}
/// <summary>
/// 分页获取数据
/// </summary>
/// <param name="where">条件表达式</param>
/// <param name="parm"></param>
/// <param name="order"></param>
/// <param name="orderEnum"></param>
/// <returns></returns>
public PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm, Expression<Func<T, object>> order, OrderByType orderEnum = OrderByType.Asc)
{
var source = Context
.Queryable<T>()
.Where(where)
.OrderByIF(orderEnum == OrderByType.Asc, order, OrderByType.Asc)
.OrderByIF(orderEnum == OrderByType.Desc, order, OrderByType.Desc);
return source.ToPage(parm);
}
public PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm, Expression<Func<T, object>> order, string orderByType)
{
return GetPages(where, parm, order, orderByType == "desc" ? OrderByType.Desc : OrderByType.Asc);
}
/// <summary>
/// 查询所有数据(无分页,请慎用)
/// </summary>
/// <returns></returns>
public List<T> GetAll(bool useCache = false, int cacheSecond = 3600)
{
return Context.Queryable<T>().WithCacheIF(useCache, cacheSecond).ToList();
}
#endregion query
/// <summary>
/// 此方法不带output返回值
/// var list = new List<SugarParameter>();
/// list.Add(new SugarParameter(ParaName, ParaValue)); input
/// </summary>
/// <param name="procedureName"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public DataTable UseStoredProcedureToDataTable(string procedureName, List<SugarParameter> parameters)
{
return Context.Ado.UseStoredProcedure().GetDataTable(procedureName, parameters);
}
/// <summary>
/// 带output返回值
/// var list = new List<SugarParameter>();
/// list.Add(new SugarParameter(ParaName, ParaValue, true)); output
/// list.Add(new SugarParameter(ParaName, ParaValue)); input
/// </summary>
/// <param name="procedureName"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public (DataTable, List<SugarParameter>) UseStoredProcedureToTuple(string procedureName, List<SugarParameter> parameters)
{
var result = (Context.Ado.UseStoredProcedure().GetDataTable(procedureName, parameters), parameters);
return result;
}
}
/// <summary>
/// 插入单条记录
/// 分页查询扩展
/// </summary>
/// <param name="entity">实体对象</param>
/// <returns>是否成功</returns>
public async Task<bool> InsertAsync(T entity)
public static class QueryableExtension
{
return await Db.Insertable(entity).ExecuteCommandAsync() > 0;
}
/// <summary>
/// 读取列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">查询表单式</param>
/// <param name="parm">分页参数</param>
/// <returns></returns>
public static PageListModel<T> ToPage<T>(this ISugarQueryable<T> source, PageQueryModel parm)
{
var page = new PageListModel<T>();
var total = 0;
page.PageSize = parm.PageSize;
page.PageIndex = parm.PageIndex;
if (string.IsNullOrEmpty(parm.Sort))
{
source.OrderByPropertyName(parm.Sort, parm.SortType.Contains("desc") ? OrderByType.Desc : OrderByType.Asc);
}
page.Result = source
//.OrderByIF(parm.Sort.IsNotEmpty(), $"{parm.Sort.ToSqlFilter()} {(!string.IsNullOrWhiteSpace(parm.SortType) && parm.SortType.Contains("desc") ? "desc" : "asc")}")
.ToPageList(parm.PageIndex, parm.PageSize, ref total);
page.TotalNum = total;
return page;
}
/// <summary>
/// 批量插入记录
/// </summary>
/// <param name="entities">实体列表</param>
/// <returns>是否成功</returns>
public async Task<bool> InsertRangeAsync(List<T> entities)
{
return await Db.Insertable(entities).ExecuteCommandAsync() > 0;
}
/// <summary>
/// 转指定实体类Dto
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="source"></param>
/// <param name="parm"></param>
/// <returns></returns>
public static PageListModel<T2> ToPage<T, T2>(this ISugarQueryable<T> source, PageQueryModel parm)
{
var page = new PageListModel<T2>();
var total = 0;
page.PageSize = parm.PageSize;
page.PageIndex = parm.PageIndex;
if (string.IsNullOrEmpty(parm.Sort))
{
source.OrderByPropertyName(parm.Sort, parm.SortType.Contains("desc") ? OrderByType.Desc : OrderByType.Asc);
}
var result = source
//.OrderByIF(parm.Sort.IsNotEmpty(), $"{parm.Sort.ToSqlFilter()} {(!string.IsNullOrWhiteSpace(parm.SortType) && parm.SortType.Contains("desc") ? "desc" : "asc")}")
.ToPageList(parm.PageIndex, parm.PageSize, ref total);
/// <summary>
/// 更新单条记录
/// </summary>
/// <param name="entity">实体对象</param>
/// <returns>是否成功</returns>
public async Task<bool> UpdateAsync(T entity)
{
return await Db.Updateable(entity).ExecuteCommandAsync() > 0;
page.TotalNum = total;
page.Result = result.Adapt<List<T2>>();
return page;
}
}
/// <summary>
/// 批量更新记录
/// </summary>
/// <param name="entities">实体列表</param>
/// <returns>是否成功</returns>
public async Task<bool> UpdateRangeAsync(List<T> entities)
{
return await Db.Updateable(entities).ExecuteCommandAsync() > 0;
}
/// <summary>
/// 根据Id删除记录软删除设置 IsDeleted = true
/// </summary>
/// <param name="id">主键Id</param>
/// <returns>是否成功</returns>
public async Task<bool> DeleteByIdAsync(long id)
{
return await Db.Deleteable<T>().In(id).IsLogic().ExecuteCommandAsync() > 0;
}
/// <summary>
/// 根据条件删除记录(软删除,设置 IsDeleted = true
/// </summary>
/// <param name="where">删除条件</param>
/// <returns>是否成功</returns>
public async Task<bool> DeleteByWhereAsync(Expression<Func<T, bool>> where)
{
return await Db.Deleteable<T>().Where(where).IsLogic().ExecuteCommandAsync() > 0;
}
/// <summary>
/// 根据条件获取记录数(自动过滤已删除数据)
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>记录数</returns>
public async Task<int> GetCountAsync(Expression<Func<T, bool>> where)
{
return await Db.Queryable<T>().Where(where).CountAsync();
}
public ISugarQueryable<T> Queryable()
{
return Db.Queryable<T>();
}
}
}