refactor: 重构项目基础架构与实体体系
- 替换原有自定义生命周期接口为通用基础服务体系 - 将所有实体基类替换为带雪花ID的SqlSugarBaseEntity - 迁移DTO到Models项目并统一管理 - 移除冗余的Repository层实现,改用通用基础服务 - 添加Yitter.IdGenerator雪花ID生成支持 - 重构SqlSugar数据库上下文与依赖注入配置 - 新增微信用户、用户勋章、背包等实体与配套服务 - 整理分页查询与结果封装类 - 优化WebApi控制器结构
This commit is contained in:
@ -1,13 +0,0 @@
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository;
|
||||
|
||||
public class AdminUserRepository : BaseRepository<AdminUser>, IAdminUserRepository
|
||||
{
|
||||
public async Task<AdminUser?> GetByUserNameAsync(string userName)
|
||||
{
|
||||
return await Db.Queryable<AdminUser>()
|
||||
.Where(x => x.UserName == userName)
|
||||
.FirstAsync();
|
||||
}
|
||||
}
|
||||
@ -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>
|
||||
/// 根据指定条件更新指定列 eg:Update(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>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
160
QYZH.InteractiveMagazine.Repository/Core/SqlSugarExtension.cs
Normal file
160
QYZH.InteractiveMagazine.Repository/Core/SqlSugarExtension.cs
Normal file
@ -0,0 +1,160 @@
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
using SqlSugar;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// sql sugar 管理器
|
||||
/// </summary>
|
||||
public static class SqlSugarExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成类文件
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
/// <param name="directoryPath">生成路径</param>
|
||||
/// <param name="nameSpace">名称空间</param>
|
||||
public static ISqlSugarClient CreateClassFile(this ISqlSugarClient db, string directoryPath, string nameSpace = "Models")
|
||||
{
|
||||
foreach (var item in db.DbMaintenance.GetTableInfoList())
|
||||
{
|
||||
string[] entityNameArray = item.Name.Split('_', StringSplitOptions.RemoveEmptyEntries).ToArray();
|
||||
string entityName = string.Join("", entityNameArray.Select(c => c.ToCamelCase()));
|
||||
db.MappingTables.Add(entityName, item.Name);
|
||||
foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
|
||||
{
|
||||
var columnNames = col.DbColumnName.ToLower().Split('_', StringSplitOptions.RemoveEmptyEntries).ToArray();
|
||||
string columnName = string.Join("", columnNames.Select(c => c.ToCamelCase()));
|
||||
db.MappingColumns.Add(columnName, col.DbColumnName, entityName);
|
||||
}
|
||||
}
|
||||
db.DbFirst.IsCreateAttribute().CreateClassFile(directoryPath, nameSpace);
|
||||
return db;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 添加全局过滤器
|
||||
/// IsDeleted
|
||||
/// </summary>
|
||||
/// <param name="db">数据库Client</param>
|
||||
/// <param name="assemblyName">程序集名称</param>
|
||||
/// <returns></returns>
|
||||
public static ISqlSugarClient SetQueryFilter(this ISqlSugarClient db, string assemblyName)
|
||||
{
|
||||
var assembly = Assembly.Load(assemblyName);
|
||||
|
||||
var modelBaseType = typeof(SqlSugarBaseEntity);
|
||||
var repoBaseType = typeof(SqlSugarBaseEntity);
|
||||
|
||||
var types = assembly.ExportedTypes
|
||||
.Where(t => (modelBaseType.IsAssignableFrom(t) || repoBaseType.IsAssignableFrom(t))
|
||||
&& t != modelBaseType && t != repoBaseType
|
||||
&& !t.IsGenericTypeDefinition)
|
||||
.ToList();
|
||||
|
||||
foreach (var entityType in types)
|
||||
{
|
||||
var property = entityType.GetProperty("IsDeleted", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
|
||||
if (property == null)
|
||||
{
|
||||
var baseType = entityType.BaseType;
|
||||
while (baseType != null && baseType != typeof(object))
|
||||
{
|
||||
property = baseType.GetProperty("IsDeleted", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
|
||||
if (property != null) break;
|
||||
baseType = baseType.BaseType;
|
||||
}
|
||||
}
|
||||
|
||||
if (property == null) continue;
|
||||
|
||||
var propertyType = property.PropertyType;
|
||||
|
||||
Expression filterExpression;
|
||||
var param = Expression.Parameter(entityType, "it");
|
||||
var propertyAccess = Expression.Property(param, property);
|
||||
|
||||
if (propertyType == typeof(bool))
|
||||
{
|
||||
filterExpression = Expression.Equal(propertyAccess, Expression.Constant(false, typeof(bool)));
|
||||
}
|
||||
else if (propertyType == typeof(bool?))
|
||||
{
|
||||
filterExpression = Expression.Equal(propertyAccess, Expression.Constant(false, typeof(bool?)));
|
||||
}
|
||||
else if (propertyType == typeof(byte))
|
||||
{
|
||||
filterExpression = Expression.Equal(propertyAccess, Expression.Constant((byte)0, typeof(byte)));
|
||||
}
|
||||
else if (propertyType == typeof(byte?))
|
||||
{
|
||||
filterExpression = Expression.Equal(propertyAccess, Expression.Constant((byte)0, typeof(byte?)));
|
||||
}
|
||||
else
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var lambda = Expression.Lambda(filterExpression, param);
|
||||
db.QueryFilter.AddTableFilter(entityType, lambda);
|
||||
}
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加创建人 创建时间 更新人 更新时间 默认值
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
public static ISqlSugarClient SetDefaultValue(this ISqlSugarClient db)
|
||||
{
|
||||
#region 创建人 创建时间 更新人 更新时间 默认值
|
||||
db.Aop.DataExecuting = (oldValue, entityInfo) =>
|
||||
{
|
||||
var entityValue = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)?.ToString();
|
||||
var currnetUserName = "";
|
||||
/*** inset生效 ***/
|
||||
if (entityInfo.OperationType == DataFilterType.InsertByObject)
|
||||
{
|
||||
if (entityInfo.PropertyName == "CreatedAt" && (string.IsNullOrWhiteSpace(entityValue) || entityValue == DateTime.MinValue.ToString()))
|
||||
entityInfo.SetValue(DateTime.Now);//修改CreateTime字段
|
||||
else if (entityInfo.PropertyName == "CreatedBy" && (string.IsNullOrWhiteSpace(entityValue)))
|
||||
entityInfo.SetValue(currnetUserName);//修改创建人字段
|
||||
else if (entityInfo.PropertyName == "IsDeleted" && string.IsNullOrWhiteSpace(entityValue))
|
||||
entityInfo.SetValue("0");//修改CreateTime字段
|
||||
|
||||
}
|
||||
|
||||
/*** update生效 ***/
|
||||
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
|
||||
{
|
||||
if (entityInfo.PropertyName == "UpdatedAt" && (string.IsNullOrWhiteSpace(entityValue) || entityValue == DateTime.MinValue.ToString()))
|
||||
entityInfo.SetValue(DateTime.Now);//修改UpdatedTime字段
|
||||
else if (entityInfo.PropertyName == "UpdatedBy" && (string.IsNullOrWhiteSpace(entityValue) || entityValue == "0"))
|
||||
entityInfo.SetValue(currnetUserName);//修改更新人字段
|
||||
}
|
||||
};
|
||||
return db;
|
||||
#endregion
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 把一个字符串转成驼峰规则的字符串
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static string ToCamelCase(this string str)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(str) && str.Length > 1)
|
||||
{
|
||||
return char.ToUpperInvariant(str[0]) + str.Substring(1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
}
|
||||
}
|
||||
51
QYZH.InteractiveMagazine.Repository/Core/SqlSugarManager.cs
Normal file
51
QYZH.InteractiveMagazine.Repository/Core/SqlSugarManager.cs
Normal file
@ -0,0 +1,51 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using QYZH.InteractiveMagazine.Repository.Core;
|
||||
using Serilog;
|
||||
using SqlSugar;
|
||||
using SqlSugar.IOC;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// sql sugar 管理器
|
||||
/// </summary>
|
||||
public static class SqlSugarManager
|
||||
{
|
||||
/// <summary>
|
||||
/// 获基础信息库对象 (用IOC这块代码不能写到IOC里面)
|
||||
/// </summary>
|
||||
public static void InitSqlSugarDb(this WebApplicationBuilder builder, IocConfig config)
|
||||
{
|
||||
builder.Services.AddSqlSugar(config);
|
||||
//配置参数
|
||||
SugarIocServices.ConfigurationSugar(db =>
|
||||
{
|
||||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||||
{
|
||||
//var param = db.GetConnectionScope(0).Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
|
||||
Log.Information($"【sql语句】{UtilMethods.GetSqlString((DbType)config.DbType, sql, pars)}\n");
|
||||
};
|
||||
|
||||
db.Aop.OnError = (ex) =>
|
||||
{
|
||||
string sql = $"【错误SQL】{UtilMethods.GetSqlString((DbType)config.DbType, ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
|
||||
Log.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
|
||||
};
|
||||
//SQL执行完
|
||||
db.Aop.OnLogExecuted = (sql, pars) =>
|
||||
{
|
||||
//执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
|
||||
};
|
||||
db.SetDefaultValue().SetQueryFilter(GetAssemblyNames());//.CreateClassFile("C:\\Model");
|
||||
});
|
||||
}
|
||||
|
||||
private static string GetAssemblyNames()
|
||||
{
|
||||
string friendlyName = AppDomain.CurrentDomain.FriendlyName;
|
||||
string[] source = friendlyName.Split('.');
|
||||
string assemblyNames = string.Join(".", source.Take(source.Count() - 1)) + ".Models";
|
||||
return assemblyNames;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository;
|
||||
|
||||
public interface IAdminUserRepository : IBaseRepository<AdminUser>
|
||||
{
|
||||
Task<AdminUser?> GetByUserNameAsync(string userName);
|
||||
}
|
||||
@ -1,88 +1,102 @@
|
||||
|
||||
using QYZH.InteractiveMagazine.Models.Dto;
|
||||
using SqlSugar;
|
||||
using System.Data;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// 基础仓储接口
|
||||
/// </summary>
|
||||
/// <typeparam name="T">实体类型</typeparam>
|
||||
public interface IBaseRepository<T> where T : class, new()
|
||||
namespace QYZH.InteractiveMagazine.Repository
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据Id获取实体
|
||||
/// </summary>
|
||||
/// <param name="id">主键Id</param>
|
||||
/// <returns>实体对象</returns>
|
||||
Task<T?> GetByIdAsync(long id);
|
||||
public interface IBaseRepository<T> : ISimpleClient<T> where T : class, new()
|
||||
{
|
||||
#region add
|
||||
int Add(T t, bool ignoreNull = true);
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有列表
|
||||
/// </summary>
|
||||
/// <returns>实体列表</returns>
|
||||
Task<List<T>> GetListAsync();
|
||||
int Insert(List<T> t);
|
||||
int Insert(T parm, Expression<Func<T, object>> iClumns = null, bool ignoreNull = true);
|
||||
|
||||
/// <summary>
|
||||
/// 根据条件获取列表
|
||||
/// </summary>
|
||||
/// <param name="where">查询条件</param>
|
||||
/// <returns>实体列表</returns>
|
||||
Task<List<T>> GetListByWhereAsync(Expression<Func<T, bool>> where);
|
||||
IInsertable<T> Insertable(T t);
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询
|
||||
/// </summary>
|
||||
/// <param name="where">查询条件</param>
|
||||
/// <param name="pageQuery">分页参数</param>
|
||||
/// <returns>分页结果</returns>
|
||||
Task<PageListModel<T>> GetPageListAsync(Expression<Func<T, bool>> where, PageQueryModel pageQuery);
|
||||
IUpdateable<T> Updateable();
|
||||
#endregion add
|
||||
|
||||
/// <summary>
|
||||
/// 插入单条记录
|
||||
/// </summary>
|
||||
/// <param name="entity">实体对象</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> InsertAsync(T entity);
|
||||
#region update
|
||||
int Update(T entity, bool ignoreNullColumns = false, object data = null);
|
||||
|
||||
/// <summary>
|
||||
/// 批量插入记录
|
||||
/// </summary>
|
||||
/// <param name="entities">实体列表</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> InsertRangeAsync(List<T> entities);
|
||||
/// <summary>
|
||||
/// 只更新表达式的值
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
int Update(T entity, Expression<Func<T, object>> expression, bool ignoreAllNull = false);
|
||||
|
||||
/// <summary>
|
||||
/// 更新单条记录
|
||||
/// </summary>
|
||||
/// <param name="entity">实体对象</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> UpdateAsync(T entity);
|
||||
int Update(T entity, Expression<Func<T, object>> expression, Expression<Func<T, bool>> where);
|
||||
|
||||
/// <summary>
|
||||
/// 批量更新记录
|
||||
/// </summary>
|
||||
/// <param name="entities">实体列表</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> UpdateRangeAsync(List<T> entities);
|
||||
int Update(Expression<Func<T, T>> columns, Expression<Func<T, bool>> where);
|
||||
Task<int> UpdateAsync(Expression<Func<T, T>> columns, Expression<Func<T, bool>> where);
|
||||
|
||||
/// <summary>
|
||||
/// 根据Id删除记录(软删除)
|
||||
/// </summary>
|
||||
/// <param name="id">主键Id</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> DeleteByIdAsync(long id);
|
||||
#endregion update
|
||||
|
||||
/// <summary>
|
||||
/// 根据条件删除记录(软删除)
|
||||
/// </summary>
|
||||
/// <param name="where">删除条件</param>
|
||||
/// <returns>是否成功</returns>
|
||||
Task<bool> DeleteByWhereAsync(Expression<Func<T, bool>> where);
|
||||
/// <summary>
|
||||
/// 事务 同步
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
/// <returns></returns>
|
||||
Task UseTranAsync(Func<Task> action);
|
||||
|
||||
/// <summary>
|
||||
/// 根据条件获取记录数
|
||||
/// </summary>
|
||||
/// <param name="where">查询条件</param>
|
||||
/// <returns>记录数</returns>
|
||||
Task<int> GetCountAsync(Expression<Func<T, bool>> where);
|
||||
/// <summary>
|
||||
/// 事务 异步
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> UseTranAsync(Func<Task<bool>> action);
|
||||
|
||||
#region delete
|
||||
IDeleteable<T> Deleteable();
|
||||
int Delete(object id, string title = "");
|
||||
int DeleteTable();
|
||||
bool Truncate();
|
||||
|
||||
#endregion delete
|
||||
|
||||
#region query
|
||||
/// <summary>
|
||||
/// 根据条件查询分页数据
|
||||
/// </summary>
|
||||
/// <param name="where"></param>
|
||||
/// <param name="parm"></param>
|
||||
/// <returns></returns>
|
||||
PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm);
|
||||
|
||||
PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm, Expression<Func<T, object>> order, OrderByType orderEnum = OrderByType.Asc);
|
||||
PageListModel<T> GetPages(Expression<Func<T, bool>> where, PageQueryModel parm, Expression<Func<T, object>> order, string orderByType);
|
||||
|
||||
bool Any(Expression<Func<T, bool>> expression);
|
||||
|
||||
ISugarQueryable<T> Queryable();
|
||||
List<T> GetAll(bool useCache = false, int cacheSecond = 3600);
|
||||
|
||||
List<T> SqlQueryToList(string sql, object obj = null);
|
||||
|
||||
/// <summary>
|
||||
/// 根据主值查询单条数据
|
||||
/// </summary>
|
||||
/// <param name="pkValue">主键值</param>
|
||||
/// <returns>泛型实体</returns>
|
||||
R GetById<R>(object pkValue) where R : class;
|
||||
|
||||
Task<R> GetByExpression<R>(Expression<Func<T, bool>> expression) where R : class;
|
||||
|
||||
Task<List<T2>> GetListByExpression<T2>(Expression<Func<T, bool>> expression) where T2 : class;
|
||||
|
||||
#endregion query
|
||||
|
||||
#region Procedure
|
||||
|
||||
DataTable UseStoredProcedureToDataTable(string procedureName, List<SugarParameter> parameters);
|
||||
|
||||
(DataTable, List<SugarParameter>) UseStoredProcedureToTuple(string procedureName, List<SugarParameter> parameters);
|
||||
|
||||
#endregion Procedure
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,14 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\QYZH.InteractiveMagazine.Common\QYZH.InteractiveMagazine.Common.csproj" />
|
||||
<ProjectReference Include="..\QYZH.InteractiveMagazine.Infrastructure\QYZH.InteractiveMagazine.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\QYZH.InteractiveMagazine.Models\QYZH.InteractiveMagazine.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
|
||||
<PackageReference Include="MySqlConnector" Version="2.5.0" />
|
||||
<PackageReference Include="SqlSugar.IOC" Version="2.0.1" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.213" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
@ -1,99 +0,0 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
using SqlSugar;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// SqlSugar 数据库上下文封装(静态类)
|
||||
/// </summary>
|
||||
public static class SqlSugarDbContext
|
||||
{
|
||||
/// <summary>
|
||||
/// SqlSugarClient 实例
|
||||
/// </summary>
|
||||
private static SqlSugarClient? _db;
|
||||
|
||||
/// <summary>
|
||||
/// 配置对象
|
||||
/// </summary>
|
||||
private static IConfiguration? _configuration;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化数据库上下文(在应用启动时调用一次)
|
||||
/// </summary>
|
||||
/// <param name="configuration">配置对象</param>
|
||||
public static void Init(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 SqlSugarClient 实例
|
||||
/// </summary>
|
||||
/// <returns>SqlSugarClient 实例</returns>
|
||||
public static SqlSugarClient GetDb()
|
||||
{
|
||||
if (_configuration == null)
|
||||
{
|
||||
throw new InvalidOperationException("请先调用 SqlSugarDbContext.Init(configuration) 进行初始化");
|
||||
}
|
||||
|
||||
if (_db == null)
|
||||
{
|
||||
lock (typeof(SqlSugarDbContext))
|
||||
{
|
||||
if (_db == null)
|
||||
{
|
||||
var connectionString = _configuration.GetConnectionString("DefaultConnection");
|
||||
if (string.IsNullOrWhiteSpace(connectionString))
|
||||
{
|
||||
throw new InvalidOperationException("未找到连接字符串 DefaultConnection");
|
||||
}
|
||||
|
||||
_db = new SqlSugarClient(new ConnectionConfig
|
||||
{
|
||||
ConnectionString = connectionString,
|
||||
DbType = DbType.MySql,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute
|
||||
},
|
||||
db =>
|
||||
{
|
||||
// 配置软删除全局过滤(继承 BaseEntity 的实体都有效)
|
||||
db.QueryFilter.AddTableFilter<BaseEntity>(it => it.IsDeleted == false);
|
||||
|
||||
// 开启日志打印
|
||||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||||
{
|
||||
Console.WriteLine($"[SQL执行] {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
|
||||
Console.WriteLine($"[SQL语句] {sql}");
|
||||
Console.WriteLine($"[SQL参数] {string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
|
||||
Console.WriteLine(new string('-', 50));
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _db;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 代码优先初始化(可选)
|
||||
/// </summary>
|
||||
/// <param name="entityTypes">实体类型数组</param>
|
||||
public static void InitializeCodeFirst(params Type[] entityTypes)
|
||||
{
|
||||
var db = GetDb();
|
||||
|
||||
// 创建数据库(如果不存在)
|
||||
db.DbMaintenance.CreateDatabase();
|
||||
|
||||
// 初始化表结构
|
||||
if (entityTypes != null && entityTypes.Length > 0)
|
||||
{
|
||||
db.CodeFirst.InitTables(entityTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user