Files
ww-jst/wmsjst/JSMachine.WMS.Domain/Repository/BaseRepository.cs
T
2026-09-02 16:31:50 +08:00

618 lines
23 KiB
C#

using JSMachine.WMS.Domain.Entity;
using JSMachine.WMS.Domain.Exstension;
using JSMachine.WMS.Domain.IRepository;
using JSMachine.WMS.Infrastructure.Helper;
using JSMachine.WMS.Infrastructure.LambdaHelp;
using Microsoft.IdentityModel.Tokens;
using NPOI.OpenXmlFormats.Dml;
using SqlSugar;
using System.Data;
using System.Linq.Expressions;
namespace JSMachine.WMS.Domain.Repository
{
/// <summary>
/// SqlSugar官方文档 https://www.donet5.com/Doc/1/1193
/// 参考 SqlSugar官方文档 数据查询->表格查询即可实现动态条件查询,可不必使用自定义的框架
/// </summary>
/// <typeparam name="TAggregateRoot"></typeparam>
public class BaseRepository<TAggregateRoot> : IBaseRepository<TAggregateRoot> where TAggregateRoot : AggregateRoot, IAggregateRoot, new()
{
private SqlSugarScope _sqlSugarScope;
public BaseRepository(SqlSugarScope sqlSugarScope)
{
_sqlSugarScope = sqlSugarScope;
}
#region Add
/// <summary>
/// 添加单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task<bool> Add(TAggregateRoot entity, SqlSugarScope sqlSugarScope = null)
{
if (sqlSugarScope == null)
return await _sqlSugarScope.Insertable(entity).InsertableExecuteCommandAsync();
else
return await sqlSugarScope.Insertable(entity).ExecuteCommandAsync()>=0;
}
/// <summary>
/// 添加单个实体
/// </summary>
/// <param name="entity"></param>
/// <param name="ignoreColumns">要忽略的字段</param>
/// <returns></returns>
public async Task<bool> Add(TAggregateRoot entity, params string[] ignoreColumns)
{
return await _sqlSugarScope.Insertable(entity).IgnoreColumns(ignoreColumns).InsertableExecuteCommandAsync();
}
/// <summary>
/// 批量插入
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public async Task<bool> Add(List<TAggregateRoot> entities)
{
return await _sqlSugarScope.Insertable(entities).InsertableExecuteCommandAsync();
}
/// <summary>
/// 字典方式添加单个实体
/// </summary>
/// <param name="tableName">表名称</param>
/// <param name="dic"></param>
/// <returns></returns>
public async Task<bool> Add(string tableName, Dictionary<string, object> dic)
{
try
{
return await _sqlSugarScope.Insertable(dic).AS(tableName).ExecuteCommandAsync() > 0;
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库插入过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return false;
}
}
/// <summary>
/// 添加之前判断指定字段是否存在,不存在则添加
/// </summary>
/// <param name="entity"></param>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<bool> AddIfNotExist(TAggregateRoot entity, Expression<Func<TAggregateRoot, bool>> expression)
{
bool bRte = await this.Exist(expression);
if (bRte)
{
return false;
}
return await Add(entity);
}
#endregion
#region Delete
/// <summary>
/// 根据Id删除记录
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<bool> DeleteById(Guid id, SqlSugarScope sqlSugarScope = null)
{
if (id == Guid.Empty)
return false;
if (sqlSugarScope == null)
return await _sqlSugarScope.Deleteable<TAggregateRoot>().In(id).DeletetableExecuteCommandAsync();
else
return await sqlSugarScope.Deleteable<TAggregateRoot>().In(id).ExecuteCommandAsync()>=0;
}
/// <summary>
/// 根据Id批量删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<bool> DeleteBatch(Guid[] ids)
{
if (ids == null || ids.Length == 0)
return false;
return await _sqlSugarScope.Deleteable<TAggregateRoot>().In(ids).DeletetableExecuteCommandAsync();
}
/// <summary>
/// 根据实体删除
/// </summary>
/// <param name="aggregateRoot"></param>
/// <returns></returns>
public async Task<bool> DeleteByEntity(TAggregateRoot aggregateRoot)
{
return await _sqlSugarScope.Deleteable(aggregateRoot).DeletetableExecuteCommandAsync();
}
/// <summary>
/// 根据实体批量删除
/// </summary>
/// <param name="aggregateRoots"></param>
/// <returns>受影响行数不等于实体数量视为删除失败</returns>
public async Task<bool> DeleteByEntity(List<TAggregateRoot> aggregateRoots)
{
return await _sqlSugarScope.Deleteable(aggregateRoots).DeletetableExecuteCommandAsync();
}
/// <summary>
/// 根据条件删除
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<bool> DeleByExpression(Expression<Func<TAggregateRoot, bool>> expression)
{
return await _sqlSugarScope.Deleteable<TAggregateRoot>().Where(expression).DeletetableExecuteCommandAsync();
}
#endregion
#region Edit
/// <summary>
/// 更改单个实体
/// </summary>
/// <param name="aggregateRoot"></param>
/// <returns></returns>
public async Task<bool> EditSingal(TAggregateRoot aggregateRoot)
{
return await _sqlSugarScope.Updateable(aggregateRoot).WhereColumns(p => p.Id).UpdateableExecuteCommandAsync();
}
/// <summary>
/// 更改单个实体但忽略指定的列
/// </summary>
/// <param name="aggregateRoot"></param>
/// <param name="ignoredColumns">忽略指定的条件</param>
/// <returns></returns>
public async Task<bool> EditSingal(TAggregateRoot aggregateRoot, Expression<Func<TAggregateRoot, object>> ignoredColumns)
{
return await _sqlSugarScope.Updateable(aggregateRoot).WhereColumns(p => p.Id).IgnoreColumns(ignoredColumns).UpdateableExecuteCommandAsync();
}
/// <summary>
/// 更改单个实体但忽略指定的列
/// </summary>
/// <param name="aggregateRoot"></param>
/// <param name="ignoredColumns">要忽略的列名</param>
/// <returns></returns>
public async Task<bool> EditSingal(TAggregateRoot aggregateRoot, string[] ignoredColumns)
{
return await _sqlSugarScope.Updateable(aggregateRoot).WhereColumns(p => p.Id).IgnoreColumns(ignoredColumns).UpdateableExecuteCommandAsync();
}
/// <summary>
/// 更改单个实体中指定的列
/// </summary>
/// <param name="aggregateRoot"></param>
/// <param name="columns">要更改的列名</param>
/// <returns></returns>
public async Task<bool> EditSingalWithSpecificCols(TAggregateRoot aggregateRoot, string[] columns)
{
return await _sqlSugarScope.Updateable(aggregateRoot).WhereColumns(p => p.Id).UpdateColumns(columns).UpdateableExecuteCommandAsync();
}
/// <summary>
/// 批量更新
/// </summary>
/// <param name="aggregateRoots"></param>
/// <returns></returns>
public async Task<bool> EditBatch(List<TAggregateRoot> aggregateRoots)
{
if (aggregateRoots == null || aggregateRoots.Count == 0)
return false;
return await _sqlSugarScope.Updateable(aggregateRoots).UpdateableExecuteCommandAsync();
}
/// <summary>
/// 快速批量更新
/// </summary>
/// <param name="aggregateRoots"></param>
/// <returns></returns>
public async Task<bool> EditBatchFast(List<TAggregateRoot> aggregateRoots)
{
if (aggregateRoots == null || aggregateRoots.Count == 0)
return false;
return await _sqlSugarScope.Fastest<TAggregateRoot>().BulkUpdateAsync(aggregateRoots) == aggregateRoots.Count;
}
/// <summary>
/// 字典方式更改
/// </summary>
/// <param name="tableName"></param>
/// <param name="dic"></param>
/// <returns></returns>
public async Task<bool> EditByDic(string tableName, Dictionary<string, object> dic)
{
return await _sqlSugarScope.Updateable<TAggregateRoot>(dic).AS(tableName).WhereColumns("Id").UpdateableExecuteCommandAsync();
}
/// <summary>
/// 字典方式批量更改
/// </summary>
/// <param name="tableName"></param>
/// <param name="dic"></param>
/// <returns></returns>
public async Task<bool> EditByDic(string tableName, List<Dictionary<string, object>> dic)
{
return await _sqlSugarScope.Updateable<TAggregateRoot>(dic).AS(tableName).WhereColumns("Id").UpdateableExecuteCommandAsync();
}
#endregion
#region Query
/// <summary>
/// 查询所有
/// </summary>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetAll()
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().ToListExAsync();
}
/// <summary>
/// 查询所有
/// </summary>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetAll(Expression<Func<TAggregateRoot, object>> orderByExpress, OrderByType orderByType)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().OrderBy(orderByExpress, orderByType).ToListExAsync();
}
/// <summary>
/// 分片查询所有
/// </summary>
/// <param name="fragmentSize"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetAllFragment(int fragmentSize = 50000)
{
try
{
List<TAggregateRoot> aggregateRoots = new();
await _sqlSugarScope.Queryable<TAggregateRoot>().ForEachAsync(p => aggregateRoots.Add(p), fragmentSize);
return aggregateRoots;
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new List<TAggregateRoot>();
}
}
/// <summary>
/// 分片查询所有
/// </summary>
/// <param name="fragmentSize"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetAllFragment(Expression<Func<TAggregateRoot, object>> orderByExpress, OrderByType orderByType, int fragmentSize = 200)
{
try
{
List<TAggregateRoot> aggregateRoots = new();
await _sqlSugarScope.Queryable<TAggregateRoot>().OrderBy(orderByExpress, orderByType).ForEachAsync(p => aggregateRoots.Add(p), fragmentSize);
return aggregateRoots;
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new List<TAggregateRoot>();
}
}
/// <summary>
/// 根据主键查询
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<TAggregateRoot> QueryByKey(string key)
{
try
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().InSingleAsync(key);
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return null;
}
}
/// <summary>
/// 查询满足条件的第一个
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<TAggregateRoot> GetSingalByExpression(Expression<Func<TAggregateRoot, bool>> expression)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().FirstExAsync(expression);
}
/// <summary>
/// 查询满足条件的第一个
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<TAggregateRoot> GetSingalByExpression(
Expression<Func<TAggregateRoot, bool>> expression,
Expression<Func<TAggregateRoot, object>> orderByExpress,
OrderByType orderByType)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().OrderBy(orderByExpress, orderByType).FirstExAsync(expression);
}
/// <summary>
/// 查询满足条件的所有实体
/// </summary>
/// <param name="aggregateRoot"></param>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetListByExpression(Expression<Func<TAggregateRoot, bool>> expression)
{
return await _sqlSugarScope.CopyNew().Queryable<TAggregateRoot>().Where(expression).ToListExAsync();
}
/// <summary>
/// 查询满足条件的所有实体(带排序功能)
/// </summary>
/// <param name="expression"></param>
/// <param name="orderByExpress"></param>
/// <param name="orderByType">Asc = 0,Desc = 1</param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetListByExpression(Expression<Func<TAggregateRoot, bool>> expression,
string filedName,
OrderByType orderByType = OrderByType.Desc)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().Where(expression).OrderBy(LambdaHelper<TAggregateRoot>.GetOrderExpression<object>(filedName), orderByType).ToListExAsync();
}
/// <summary>
/// 通过实体查询满足条件的数据
/// </summary>
/// <param name="aggregateRoot"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetListWhereClass(TAggregateRoot aggregateRoot)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().WhereClass(aggregateRoot, true).ToListExAsync();
}
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pageQueryCondition">当前页码</param>
public async Task<PagedResult<TAggregateRoot>> QueryByPage(PageQueryCondition pageQueryCondition)
{
try
{
RefAsync<int> total = 0;
List<TAggregateRoot> data = await _sqlSugarScope.Queryable<TAggregateRoot>()
.Where(pageQueryCondition.Filters)
.OrderBy(LambdaHelper<TAggregateRoot>.GetOrderExpression<object>(pageQueryCondition.OrderByFiled), pageQueryCondition.OrderByType)
.ToPageListAsync(pageQueryCondition.CurrentPage, pageQueryCondition.PageSize, total);
return new PagedResult<TAggregateRoot>(total, pageQueryCondition.PageSize, pageQueryCondition.CurrentPage, data);
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new PagedResult<TAggregateRoot>();
}
}
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pageQueryCondition">当前页码</param>
public async Task<PagedResult<TAggregateRoot>> QueryByPage(Expression<Func<TAggregateRoot,bool>> expression,int pageSize,int currentPage,string orderByFiled,OrderByType orderByType)
{
try
{
RefAsync<int> total = 0;
List<TAggregateRoot> data = await _sqlSugarScope.Queryable<TAggregateRoot>()
.Where(expression)
.OrderBy(LambdaHelper<TAggregateRoot>.GetOrderExpression<object>(orderByFiled), orderByType)
.ToPageListAsync(currentPage, pageSize, total);
return new PagedResult<TAggregateRoot>(total, pageSize, currentPage, data);
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new PagedResult<TAggregateRoot>();
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<bool> Exist(Expression<Func<TAggregateRoot, bool>> expression)
{
try
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().AnyAsync(expression);
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return false;
}
}
public async Task<int> Count()
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().CountExAsync();
}
public async Task<int> Count(Expression<Func<TAggregateRoot, bool>> expression)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().CountExAsync(expression);
}
public async Task<List<TAggregateRoot>> QueryByIds(Guid[] ids)
{
return await _sqlSugarScope.Queryable<TAggregateRoot>().Where(p => ids.Contains(p.Id)).ToListExAsync();
}
#endregion
#region RawSql sql操作
/// <summary>
/// sql查询,带参数 参数示例 select * from table where id=@id and name=@name 则字典的key为 "@id"
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParam"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetBySql(string sql, Dictionary<string, object> sqlParam)
{
return await _sqlSugarScope.SqlQueryable<TAggregateRoot>(sql).AddParameters(sqlParam?.Select(p => new SugarParameter(p.Key, p.Value)).ToList()).ToListExAsync();
}
/// <summary>
/// sql查询,不带参数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public async Task<List<TAggregateRoot>> GetBySql(string sql)
{
return await _sqlSugarScope.SqlQueryable<TAggregateRoot>(sql).ToListExAsync();
}
/// <summary>
/// sql查询匿名类型
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public async Task<List<dynamic>> GetDynamicsBysql(string sql)
{
try
{
return await _sqlSugarScope.SqlQueryable<dynamic>(sql).ToListAsync();
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new List<dynamic>();
}
}
/// <summary>
/// sql查询匿名类型,附带参数 参数示例 select * from table where id=@id and name=@name 则字典的key为 "@id"
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParam"></param>
/// <returns></returns>
public async Task<List<dynamic>> GetDynamicsBysql(string sql, Dictionary<string, object> sqlParam)
{
try
{
return await _sqlSugarScope.SqlQueryable<dynamic>(sql).AddParameters(sqlParam?.Select(p => new SugarParameter(p.Key, p.Value)).ToList()).ToListAsync();
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new List<dynamic>();
}
}
/// <summary>
/// 通过sql查询DataTable
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public async Task<DataTable> GetDataTableBysql(string sql)
{
try
{
return await _sqlSugarScope.Ado.GetDataTableAsync(sql);
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return new DataTable();
}
}
/// <summary>
/// 通过sql查询DataTable, 参数示例 select * from table where id=@id and name=@name 则字典的key为 "@id"
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParam"></param>
/// <returns></returns>
public async Task<DataTable> GetDataTableBysql(string sql, Dictionary<string, object> sqlParam)
{
try
{
return await _sqlSugarScope.Ado.GetDataTableAsync(sql, sqlParam?.Select(p => new SugarParameter(p.Key, p.Value)).ToList());
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库查询过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return null;
}
}
/// <summary>
/// 执行原生sql
/// </summary>
/// <param name="sql"></param>
/// <param name="params"></param>
/// <returns></returns>
public async Task<bool> ExcuteSql(string sql, params SugarParameter[] @params)
{
try
{
await _sqlSugarScope.Ado.ExecuteCommandAsync(sql, @params);
return true;
}
catch (Exception ex)
{
LogHelper.Error($"执行数据库原生sql过程中发生错误,{ex.Message}\n{ex.StackTrace}");
return false;
}
}
#endregion
#region 事务操作
public async Task BeginTran(SqlSugarScope sqlSugarScope)
{
LogHelper.Info($"开始事务 {sqlSugarScope.ContextID}");
await sqlSugarScope.AsTenant().BeginTranAsync();
}
public async Task CommitTran(SqlSugarScope sqlSugarScope)
{
LogHelper.Info($"提交事务 {sqlSugarScope.ContextID}");
await sqlSugarScope.AsTenant().CommitTranAsync();
}
public async Task RollbackTran(SqlSugarScope sqlSugarScope)
{
LogHelper.Info($"回滚事务 {sqlSugarScope.ContextID}");
await sqlSugarScope.AsTenant().RollbackTranAsync();
}
public SqlSugarTransaction UseTranAsync()
{
return _sqlSugarScope.UseTran();
}
#endregion
}
}