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