From b3334d2084f4766b678bac93136a6ffe054acd41 Mon Sep 17 00:00:00 2001 From: "guoshun.du" Date: Fri, 1 Aug 2025 17:48:09 +0800 Subject: [PATCH 1/2] =?UTF-8?q?*=E6=94=AF=E6=8C=81=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E5=90=8E=E4=BA=8B=E4=BB=B6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SugarProvider/SqlSugarProvider.cs | 35 +++ .../SugarProvider/SqlSugarScopeProvider.cs | 35 ++- .../SqlSugar/Interface/ISqlSugarClient.cs | 46 +++- .../SqlSugar/Interface/ITenant.cs | 23 ++ Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs | 252 +++++++++++------- Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs | 34 +++ Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs | 18 ++ 7 files changed, 333 insertions(+), 110 deletions(-) diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs index 3d3e27a48..e0a478b68 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs @@ -1877,6 +1877,41 @@ namespace SqlSugar await _ThenMapperAsync(pageList, action); }); } + + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + public void AppendTranSuccessEvent(Action action) + { + Root.AppendTranSuccessEvent(action); + } + + /// + /// 减少事务成功后事件 + /// + /// + public void SubtractTranSuccessEvent(Action action) + { + Root.SubtractTranSuccessEvent(action); + } + + /// + /// 清空事务成功后事件 + /// + public void RemoveTranSuccessEvent() + { + Root.RemoveTranSuccessEvent(); + } + + /// + /// 调用事务成功后事件 + /// + public void InvokeTranSuccessEvent() + { + Root.InvokeTranSuccessEvent(); + } #endregion } } diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs index 06ed7440c..1b896d7f9 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; namespace SqlSugar { - public class SqlSugarScopeProvider:ISqlSugarClient + public class SqlSugarScopeProvider : ISqlSugarClient { internal SqlSugarProvider conn; internal string initThreadMainId; @@ -864,6 +864,39 @@ namespace SqlSugar { ScopedContext.ClearTracking(); } + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + public void AppendTranSuccessEvent(Action action) + { + ScopedContext.AppendTranSuccessEvent(action); + } + + /// + /// 减少事务成功后事件 + /// + /// + public void SubtractTranSuccessEvent(Action action) + { + ScopedContext.SubtractTranSuccessEvent(action); + } + + /// + /// 清空事务成功后事件 + /// + public void RemoveTranSuccessEvent() + { + ScopedContext.RemoveTranSuccessEvent(); + } + + /// + /// 调用事务成功后事件 + /// + public void InvokeTranSuccessEvent() + { + ScopedContext.InvokeTranSuccessEvent(); + } #endregion } } \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs b/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs index d64c6c040..9e008af2c 100644 --- a/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs +++ b/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs @@ -49,10 +49,10 @@ namespace SqlSugar Task AsyncLock(int timeOutSeconds = 30); DynamicBuilder DynamicBuilder(); void ClearTracking(); - void Tracking(T data) where T : class, new(); + void Tracking(T data) where T : class, new(); void Tracking(List data) where T : class, new(); SqlSugarClient CopyNew(); - T CreateContext(bool isTran=true) where T : SugarUnitOfWork, new(); + T CreateContext(bool isTran = true) where T : SugarUnitOfWork, new(); SugarUnitOfWork CreateContext(bool isTran = true); SplitTableContext SplitHelper(Type entityType); SplitTableContext SplitHelper() where T : class, new(); @@ -67,6 +67,28 @@ namespace SqlSugar void Open(); void Close(); ITenant AsTenant(); + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + void AppendTranSuccessEvent(Action action); + + /// + /// 减少事务成功后事件 + /// + /// + void SubtractTranSuccessEvent(Action action); + + /// + /// 清空事务成功后事件 + /// + void RemoveTranSuccessEvent(); + + /// + /// 调用事务成功后事件 + /// + void InvokeTranSuccessEvent(); #endregion #region Insertable @@ -143,17 +165,17 @@ namespace SqlSugar where T4 : class, new(); ISugarQueryable Queryable(); ISugarQueryable Queryable(ISugarQueryable queryable); - ISugarQueryable Queryable(ISugarQueryable queryable,string shortName); + ISugarQueryable Queryable(ISugarQueryable queryable, string shortName); ISugarQueryable Queryable(string shortName); #endregion #region Saveable GridSaveProvider GridSave(List saveList) where T : class, new(); - GridSaveProvider GridSave(List oldList,List saveList) where T : class, new(); + GridSaveProvider GridSave(List oldList, List saveList) where T : class, new(); IStorageable Storageable(T[] dataList) where T : class, new(); IStorageable Storageable(IList dataList) where T : class, new(); - StorageableDataTable Storageable(List> dictionaryList, string tableName); - StorageableDataTable Storageable(Dictionary dictionary, string tableName); + StorageableDataTable Storageable(List> dictionaryList, string tableName); + StorageableDataTable Storageable(Dictionary dictionary, string tableName); IStorageable Storageable(List dataList) where T : class, new(); IStorageable Storageable(T data) where T : class, new(); StorageableDataTable Storageable(DataTable data); @@ -226,23 +248,23 @@ namespace SqlSugar #region ThenMapper void ThenMapper(IEnumerable list, Action action); - Task ThenMapperAsync(IEnumerable list, Func action); + Task ThenMapperAsync(IEnumerable list, Func action); #endregion #region Nav CUD InsertNavTaskInit InsertNav(T data) where T : class, new(); InsertNavTaskInit InsertNav(List datas) where T : class, new(); - InsertNavTaskInit InsertNav(T data,InsertNavRootOptions rootOptions) where T : class, new(); + InsertNavTaskInit InsertNav(T data, InsertNavRootOptions rootOptions) where T : class, new(); InsertNavTaskInit InsertNav(List datas, InsertNavRootOptions rootOptions) where T : class, new(); DeleteNavTaskInit DeleteNav(T data) where T : class, new(); DeleteNavTaskInit DeleteNav(List datas) where T : class, new(); - DeleteNavTaskInit DeleteNav(Expression> whereExpression) where T : class, new(); + DeleteNavTaskInit DeleteNav(Expression> whereExpression) where T : class, new(); DeleteNavTaskInit DeleteNav(T data, DeleteNavRootOptions options) where T : class, new(); DeleteNavTaskInit DeleteNav(List datas, DeleteNavRootOptions options) where T : class, new(); DeleteNavTaskInit DeleteNav(Expression> whereExpression, DeleteNavRootOptions options) where T : class, new(); - UpdateNavTaskInit UpdateNav(T data) where T : class, new (); - UpdateNavTaskInit UpdateNav(List datas) where T : class, new (); - UpdateNavTaskInit UpdateNav(T data,UpdateNavRootOptions rootOptions) where T : class, new(); + UpdateNavTaskInit UpdateNav(T data) where T : class, new(); + UpdateNavTaskInit UpdateNav(List datas) where T : class, new(); + UpdateNavTaskInit UpdateNav(T data, UpdateNavRootOptions rootOptions) where T : class, new(); UpdateNavTaskInit UpdateNav(List datas, UpdateNavRootOptions rootOptions) where T : class, new(); #endregion diff --git a/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs b/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs index 127971bd2..82b8a0c8e 100644 --- a/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs +++ b/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs @@ -27,6 +27,7 @@ namespace SqlSugar DbResult UseTran(Func action, Action errorCallBack = null); Task> UseTranAsync(Func> action, Action errorCallBack = null); + void AddConnection(ConnectionConfig connection); SqlSugarProvider GetConnection(object configId); void RemoveConnection(object configId); @@ -47,5 +48,27 @@ namespace SqlSugar void Close(); void Open(); + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + void AppendTranSuccessEvent(Action action); + + /// + /// 减少事务成功后事件 + /// + /// + void SubtractTranSuccessEvent(Action action); + + /// + /// 清空事务成功后事件 + /// + void RemoveTranSuccessEvent(); + + /// + /// 调用事务成功后事件 + /// + void InvokeTranSuccessEvent(); } } diff --git a/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs b/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs index 4d55c87e4..e5686793e 100644 --- a/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs +++ b/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs @@ -6,6 +6,7 @@ using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; +using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -27,6 +28,10 @@ namespace SqlSugar private IgnoreColumnList _IgnoreColumns; private IgnoreColumnList _IgnoreInsertColumns; private Action _configAction; + /// + /// 事务成功事件,当事务提交成功后,触发此事件 + /// + private event Action _TranSuccessEvent; internal Guid? AsyncId { get; set; } internal bool? IsSingleInstance { get; set; } @@ -49,9 +54,9 @@ namespace SqlSugar _AllClients = configs.Select(it => new SugarTenant() { ConnectionConfig = it }).ToList(); ; _AllClients.First(it => it.ConnectionConfig.ConfigId == config.ConfigId).Context = this.Context; } - public SqlSugarClient(ConnectionConfig config ,Action configAction) + public SqlSugarClient(ConnectionConfig config, Action configAction) { - _configAction=configAction; + _configAction = configAction; Check.Exception(config == null, "ConnectionConfig config is null"); InitContext(config); configAction(this); @@ -71,7 +76,7 @@ namespace SqlSugar #endregion #region Global variable - public SugarActionType SugarActionType { get { return this.Context.SugarActionType; }set { this.Context.SugarActionType = value; } } + public SugarActionType SugarActionType { get { return this.Context.SugarActionType; } set { this.Context.SugarActionType = value; } } public SqlSugarProvider Context { get { return GetContext(); } } public bool IsSystemTablesConfig => this.Context.IsSystemTablesConfig; public ConnectionConfig CurrentConnectionConfig { get { return _CurrentConnectionConfig; } set { _CurrentConnectionConfig = value; } } @@ -87,7 +92,7 @@ namespace SqlSugar #region SimpleClient - public T CreateContext(bool isTran=true) where T : SugarUnitOfWork, new() + public T CreateContext(bool isTran = true) where T : SugarUnitOfWork, new() { T result = new T(); _CreateContext(isTran, result); @@ -111,7 +116,7 @@ namespace SqlSugar { value.GetType().GetProperty("Context").SetValue(value, this); } - else + else { value.GetType().GetProperty("Context").SetValue(value, this.GetConnection(tenantAttribute.configId)); } @@ -124,7 +129,7 @@ namespace SqlSugar SugarUnitOfWork sugarUnitOf = new SugarUnitOfWork(); return _CreateContext(isTran, sugarUnitOf); } - + private SugarUnitOfWork _CreateContext(bool isTran, SugarUnitOfWork sugarUnitOf) { sugarUnitOf.Db = this; @@ -139,7 +144,7 @@ namespace SqlSugar { return this.Context.GetSimpleClient(); } - public RepositoryType GetRepository() where RepositoryType : ISugarRepository , new() + public RepositoryType GetRepository() where RepositoryType : ISugarRepository, new() { Type type = typeof(RepositoryType); var isAnyParamter = type.GetConstructors().Any(z => z.GetParameters().Any()); @@ -162,7 +167,7 @@ namespace SqlSugar #endregion #region Insertable - public IInsertable> InsertableByDynamic(object insertDynamicObject) + public IInsertable> InsertableByDynamic(object insertDynamicObject) { return this.Context.InsertableByDynamic(insertDynamicObject); } @@ -177,7 +182,7 @@ namespace SqlSugar public IInsertable Insertable(dynamic insertDynamicObject) where T : class, new() { - if (insertDynamicObject is IList) + if (insertDynamicObject is IList) { return this.Context.Insertable((insertDynamicObject as IList).ToList()); } @@ -191,8 +196,8 @@ namespace SqlSugar public IInsertable Insertable(T insertObj) where T : class, new() { - Check.ExceptionEasy(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() ","需要Class,new()约束,并且类属性中不能有required修饰符"); - if (typeof(T).Name == "Object") + Check.ExceptionEasy(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() ", "需要Class,new()约束,并且类属性中不能有required修饰符"); + if (typeof(T).Name == "Object") { Check.ExceptionEasy("Object type use db.InsertableByObject(obj).ExecuteCommand()", "检测到T为Object类型,请使用 db.InsertableByObject(obj).ExecuteCommand(),Insertable不支持object,InsertableByObject可以(缺点:功能比较少)"); } @@ -209,9 +214,9 @@ namespace SqlSugar #region Queryable #region Nav CUD - public InsertNavTaskInit InsertNav(T data) where T : class, new() + public InsertNavTaskInit InsertNav(T data) where T : class, new() { - return this.Context.InsertNav(data); + return this.Context.InsertNav(data); } public InsertNavTaskInit InsertNav(List datas) where T : class, new() { @@ -235,7 +240,7 @@ namespace SqlSugar } public DeleteNavTaskInit DeleteNav(Expression> whereExpression) where T : class, new() { - return this.Context.DeleteNav(whereExpression); + return this.Context.DeleteNav(whereExpression); } public DeleteNavTaskInit DeleteNav(T data, DeleteNavRootOptions options) where T : class, new() @@ -255,13 +260,13 @@ namespace SqlSugar { return this.Context.UpdateNav(data); } - public UpdateNavTaskInit UpdateNav(List datas,UpdateNavRootOptions rootOptions) where T : class, new() + public UpdateNavTaskInit UpdateNav(List datas, UpdateNavRootOptions rootOptions) where T : class, new() { - return this.Context.UpdateNav(datas, rootOptions); + return this.Context.UpdateNav(datas, rootOptions); } public UpdateNavTaskInit UpdateNav(T data, UpdateNavRootOptions rootOptions) where T : class, new() { - return this.Context.UpdateNav(data,rootOptions); + return this.Context.UpdateNav(data, rootOptions); } public UpdateNavTaskInit UpdateNav(List datas) where T : class, new() { @@ -270,34 +275,34 @@ namespace SqlSugar #endregion #region Union - public ISugarQueryable Union(List> queryables) where T : class + public ISugarQueryable Union(List> queryables) where T : class { return this.Context.Union(queryables); } - public ISugarQueryable Union(params ISugarQueryable[] queryables) where T : class + public ISugarQueryable Union(params ISugarQueryable[] queryables) where T : class { return this.Context.Union(queryables); } - public ISugarQueryable UnionAll(List> queryables) where T : class + public ISugarQueryable UnionAll(List> queryables) where T : class { return this.Context.UnionAll(queryables); } - public ISugarQueryable UnionAll(params ISugarQueryable[] queryables) where T : class + public ISugarQueryable UnionAll(params ISugarQueryable[] queryables) where T : class { return this.Context.UnionAll(queryables); } #endregion - public QueryMethodInfo QueryableByObject(Type entityType) + public QueryMethodInfo QueryableByObject(Type entityType) { return this.Context.QueryableByObject(entityType); } - public QueryMethodInfo QueryableByObject(Type entityType,string shortName) + public QueryMethodInfo QueryableByObject(Type entityType, string shortName) { - return this.Context.QueryableByObject(entityType,shortName); + return this.Context.QueryableByObject(entityType, shortName); } public ISugarQueryable MasterQueryable() { @@ -505,16 +510,16 @@ namespace SqlSugar { return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinType1, joinExpression1, joinType2, joinExpression2).With(SqlWith.Null); } - public ISugarQueryable Queryable(ISugarQueryable joinQueryable1, ISugarQueryable joinQueryable2, ISugarQueryable joinQueryable3, ISugarQueryable joinQueryable4, - JoinType joinType1, Expression> joinExpression1, + public ISugarQueryable Queryable(ISugarQueryable joinQueryable1, ISugarQueryable joinQueryable2, ISugarQueryable joinQueryable3, ISugarQueryable joinQueryable4, + JoinType joinType1, Expression> joinExpression1, JoinType joinType2, Expression> joinExpression2, JoinType joinType3, Expression> joinExpression3) where T : class, new() where T2 : class, new() where T3 : class, new() - where T4 : class ,new () + where T4 : class, new() { - return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinQueryable4, joinType1, joinExpression1, joinType2, joinExpression2,joinType3, joinExpression3).With(SqlWith.Null); + return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinQueryable4, joinType1, joinExpression1, joinType2, joinExpression2, joinType3, joinExpression3).With(SqlWith.Null); } public ISugarQueryable Queryable() @@ -522,20 +527,20 @@ namespace SqlSugar return this.Context.Queryable(); } - public ISugarQueryable Queryable(ISugarQueryable queryable) + public ISugarQueryable Queryable(ISugarQueryable queryable) { - - var result= this.Context.Queryable(queryable); + + var result = this.Context.Queryable(queryable); var QueryBuilder = queryable.QueryBuilder; result.QueryBuilder.IsQueryInQuery = true; - var appendIndex = result.QueryBuilder.Parameters==null?1:result.QueryBuilder.Parameters.Count+1; - result.QueryBuilder.WhereIndex = (QueryBuilder.WhereIndex+1); - result.QueryBuilder.LambdaExpressions.ParameterIndex = (QueryBuilder.LambdaExpressions.ParameterIndex+ appendIndex); + var appendIndex = result.QueryBuilder.Parameters == null ? 1 : result.QueryBuilder.Parameters.Count + 1; + result.QueryBuilder.WhereIndex = (QueryBuilder.WhereIndex + 1); + result.QueryBuilder.LambdaExpressions.ParameterIndex = (QueryBuilder.LambdaExpressions.ParameterIndex + appendIndex); return result; } - public ISugarQueryable Queryable(ISugarQueryable queryable,string shortName) - { - return this.Context.Queryable(queryable,shortName); + public ISugarQueryable Queryable(ISugarQueryable queryable, string shortName) + { + return this.Context.Queryable(queryable, shortName); } public ISugarQueryable Queryable(string shortName) @@ -548,7 +553,7 @@ namespace SqlSugar #region Saveable public GridSaveProvider GridSave(List saveList) where T : class, new() { - return this.Context.GridSave(saveList); + return this.Context.GridSave(saveList); } public GridSaveProvider GridSave(List oldList, List saveList) where T : class, new() { @@ -558,7 +563,7 @@ namespace SqlSugar { return this.Context.Storageable(data); } - public StorageableDataTable Storageable(List> dictionaryList,string tableName) + public StorageableDataTable Storageable(List> dictionaryList, string tableName) { DataTable dt = this.Context.Utilities.DictionaryListToDataTable(dictionaryList); dt.TableName = tableName; @@ -586,7 +591,7 @@ namespace SqlSugar public IStorageable Storageable(T data) where T : class, new() { Check.Exception(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() "); - return this.Context.Storageable(new List { data}); + return this.Context.Storageable(new List { data }); } [Obsolete("use Storageable")] @@ -606,17 +611,17 @@ namespace SqlSugar #endregion #region Reportable - public IReportable Reportable(T data) + public IReportable Reportable(T data) { return this.Context.Reportable(data); } - public IReportable Reportable(List list) + public IReportable Reportable(List list) { return this.Context.Reportable(list); } - public IReportable Reportable(T [] array) + public IReportable Reportable(T[] array) { - return this.Context.Reportable(array); + return this.Context.Reportable(array); } #endregion @@ -742,7 +747,7 @@ namespace SqlSugar public IUpdateable Updateable(dynamic updateDynamicObject) where T : class, new() { - if (updateDynamicObject is IList) + if (updateDynamicObject is IList) { return this.Context.Updateable((updateDynamicObject as IList).ToList()); } @@ -836,16 +841,16 @@ namespace SqlSugar { this.Context.ThenMapper(list, action); } - public Task ThenMapperAsync(IEnumerable list, Func action) + public Task ThenMapperAsync(IEnumerable list, Func action) { - return this.Context.ThenMapperAsync(list,action); + return this.Context.ThenMapperAsync(list, action); } #endregion #region More api public string[] GetCurrentConfigIds() { - return _AllClients.Select(it=>it.ConnectionConfig.ConfigId+string.Empty).ToArray(); + return _AllClients.Select(it => it.ConnectionConfig.ConfigId + string.Empty).ToArray(); } public IContextMethods Utilities { get { return this.Context.Utilities; } set { this.Context.Utilities = value; } } public AopProvider Aop => this.Context.Aop; @@ -859,24 +864,24 @@ namespace SqlSugar #region TenantManager public ITenant AsTenant() { - var tenant= this as ITenant; + var tenant = this as ITenant; return tenant; } - public SqlSugarTransaction UseTran() + public SqlSugarTransaction UseTran() { return new SqlSugarTransaction(this); } - public void RemoveConnection(dynamic configId) + public void RemoveConnection(dynamic configId) { - var removeData= this._AllClients.FirstOrDefault(it => ((object)it.ConnectionConfig.ConfigId).ObjToString()== ((object)configId).ObjToString()); - object currentId= this.CurrentConnectionConfig.ConfigId; - if (removeData != null) + var removeData = this._AllClients.FirstOrDefault(it => ((object)it.ConnectionConfig.ConfigId).ObjToString() == ((object)configId).ObjToString()); + object currentId = this.CurrentConnectionConfig.ConfigId; + if (removeData != null) { - if (removeData.Context.Ado.IsAnyTran()) + if (removeData.Context.Ado.IsAnyTran()) { - Check.ExceptionEasy("RemoveConnection error has tran",$"删除失败{removeData.ConnectionConfig.ConfigId}存在未提交事务"); + Check.ExceptionEasy("RemoveConnection error has tran", $"删除失败{removeData.ConnectionConfig.ConfigId}存在未提交事务"); } - else if (((object)removeData.ConnectionConfig.ConfigId).ObjToString()== currentId.ObjToString()) + else if (((object)removeData.ConnectionConfig.ConfigId).ObjToString() == currentId.ObjToString()) { Check.ExceptionEasy("Default ConfigId cannot be deleted", $"默认库不能删除{removeData.ConnectionConfig.ConfigId}"); } @@ -906,7 +911,7 @@ namespace SqlSugar }); } } - public SqlSugarProvider GetConnectionWithAttr() + public SqlSugarProvider GetConnectionWithAttr() { var attr = typeof(T).GetCustomAttribute(); if (attr == null) @@ -933,17 +938,17 @@ namespace SqlSugar public SqlSugarProvider GetConnection(object configId) { InitTenant(); - var db = this._AllClients.FirstOrDefault(it =>Convert.ToString(it.ConnectionConfig.ConfigId) ==Convert.ToString(configId)); + var db = this._AllClients.FirstOrDefault(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId)); if (db == null) { - Check.Exception(true, "ConfigId was not found {0}", configId+""); + Check.Exception(true, "ConfigId was not found {0}", configId + ""); } if (db.Context == null) { db.Context = new SqlSugarProvider(db.ConnectionConfig); } - var intiAop=db.Context.Aop; - if (db.Context.CurrentConnectionConfig.AopEvents == null) + var intiAop = db.Context.Aop; + if (db.Context.CurrentConnectionConfig.AopEvents == null) { db.Context.CurrentConnectionConfig.AopEvents = new AopEvents(); } @@ -952,7 +957,7 @@ namespace SqlSugar db.Context.Ado.BeginTran(); } db.Context.Root = this; - if (db.Context.MappingTables == null) + if (db.Context.MappingTables == null) { db.Context.MappingTables = new MappingTableList(); } @@ -969,20 +974,20 @@ namespace SqlSugar InitTenant(); var db = this._AllClients.FirstOrDefault(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId)); return db != null; - + } public void ChangeDatabase(object configId) { - configId =Convert.ToString(configId); + configId = Convert.ToString(configId); var isLog = _Context.Ado.IsEnableLogEvent; - Check.Exception(!_AllClients.Any(it =>Convert.ToString( it.ConnectionConfig.ConfigId) ==Convert.ToString( configId)), "ConfigId was not found {0}", configId+""); - InitTenant(_AllClients.First(it => Convert.ToString(it.ConnectionConfig.ConfigId )==Convert.ToString( configId))); + Check.Exception(!_AllClients.Any(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId)), "ConfigId was not found {0}", configId + ""); + InitTenant(_AllClients.First(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId))); if (this._IsAllTran) this.Ado.BeginTran(); if (this._IsOpen) this.Open(); _Context.Ado.IsEnableLogEvent = isLog; - if (_CurrentConnectionConfig.AopEvents==null) + if (_CurrentConnectionConfig.AopEvents == null) _CurrentConnectionConfig.AopEvents = new AopEvents(); } public void ChangeDatabase(Func changeExpression) @@ -1004,7 +1009,7 @@ namespace SqlSugar _IsAllTran = true; AllClientEach(it => it.Ado.BeginTran()); } - + public void BeginTran(IsolationLevel iso) { _IsAllTran = true; @@ -1016,7 +1021,7 @@ namespace SqlSugar _IsAllTran = true; await AllClientEachAsync(async it => await it.Ado.BeginTranAsync()); } - + public async Task BeginTranAsync(IsolationLevel iso) { _IsAllTran = true; @@ -1033,13 +1038,15 @@ namespace SqlSugar { it.Ado.CommitTran(); } - catch + catch { SugarRetry.Execute(() => it.Ado.CommitTran(), new TimeSpan(0, 0, 5), 3); } - + }); _IsAllTran = false; + this.InvokeTranSuccessEvent(); + this.RemoveTranSuccessEvent(); } public async Task CommitTranAsync() @@ -1059,6 +1066,8 @@ namespace SqlSugar }); _IsAllTran = false; + this.InvokeTranSuccessEvent(); + this.RemoveTranSuccessEvent(); } public DbResult UseTran(Action action, Action errorCallBack = null) { @@ -1141,7 +1150,7 @@ namespace SqlSugar try { this.BeginTran(); - T data=default(T); + T data = default(T); if (action != null) data = await action(); this.CommitTran(); @@ -1165,14 +1174,14 @@ namespace SqlSugar public void RollbackTran() { this.Context.Ado.RollbackTran(); - AllClientEach(it => + AllClientEach(it => { try { it.Ado.RollbackTran(); } - catch + catch { SugarRetry.Execute(() => it.Ado.RollbackTran(), new TimeSpan(0, 0, 5), 3); } @@ -1217,14 +1226,15 @@ namespace SqlSugar { AllClientEach(it => it.Ado.RollbackTran()); AllClientEach(it => it.Dispose()); + this.RemoveTranSuccessEvent(); } #endregion #region Cache - public SugarCacheProvider DataCache - { - get { return this.Context.DataCache; } + public SugarCacheProvider DataCache + { + get { return this.Context.DataCache; } } #endregion @@ -1233,46 +1243,46 @@ namespace SqlSugar { return this.Context.DynamicBuilder(); } - public void Tracking(T data) where T : class, new() + public void Tracking(T data) where T : class, new() { this.Context.Tracking(data); } - public void ClearTracking() + public void ClearTracking() { this.Context.ClearTracking(); } - public void Tracking(List datas) where T : class, new() + public void Tracking(List datas) where T : class, new() { this.Context.Tracking(datas); } public SqlSugarClient CopyNew() { - if(_AllClients!=null&&_AllClients.Count>1&& _configAction != null) + if (_AllClients != null && _AllClients.Count > 1 && _configAction != null) { List connections = new List(); foreach (var item in _AllClients) { connections.Add(UtilMethods.CopyConfig(item.ConnectionConfig)); } - var newDb= new SqlSugarClient(connections, _configAction); + var newDb = new SqlSugarClient(connections, _configAction); newDb.QueryFilter = this.QueryFilter; return newDb; } SqlSugarClient result; - if(_configAction!=null) - result=new SqlSugarClient(UtilMethods.CopyConfig(this.Ado.Context.CurrentConnectionConfig),_configAction); + if (_configAction != null) + result = new SqlSugarClient(UtilMethods.CopyConfig(this.Ado.Context.CurrentConnectionConfig), _configAction); else result = new SqlSugarClient(UtilMethods.CopyConfig(this.Ado.Context.CurrentConnectionConfig)); result.QueryFilter = this.QueryFilter; - if (_AllClients != null) + if (_AllClients != null) { foreach (var item in _AllClients) { - if (!result.IsAnyConnection(item.ConnectionConfig.ConfigId)) + if (!result.IsAnyConnection(item.ConnectionConfig.ConfigId)) { - result.AddConnection(UtilMethods.CopyConfig(item.ConnectionConfig)); + result.AddConnection(UtilMethods.CopyConfig(item.ConnectionConfig)); } } } @@ -1290,6 +1300,54 @@ namespace SqlSugar { this.Context.InitMappingInfo(typeof(T)); } + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + public void AppendTranSuccessEvent(Action action) + { + _TranSuccessEvent += action; + } + + /// + /// 减少事务成功后事件 + /// + /// + public void SubtractTranSuccessEvent(Action action) + { + _TranSuccessEvent -= action; + } + + /// + /// 清空事务成功后事件 + /// + public void RemoveTranSuccessEvent() + { + if (_TranSuccessEvent != null) + { + //使用取消订阅的方式,这样更为稳妥 + var actionBody = _TranSuccessEvent.GetInvocationList(); + if (actionBody.Length > 0) + { + foreach (Action handler in actionBody) + { + _TranSuccessEvent -= handler; + } + } + } + } + + /// + /// 调用事务成功后事件 + /// + public void InvokeTranSuccessEvent() + { + if (_TranSuccessEvent != null) + { + _TranSuccessEvent(this); + } + } #endregion #region Helper @@ -1297,11 +1355,11 @@ namespace SqlSugar { return this.Context.AsyncLock(timeOutSeconds); } - public SplitTableContext SplitHelper() where T:class,new() + public SplitTableContext SplitHelper() where T : class, new() { return this.Context.SplitHelper(); } - public SplitTableContext SplitHelper(Type entityType) + public SplitTableContext SplitHelper(Type entityType) { return this.Context.SplitHelper(entityType); } @@ -1326,7 +1384,7 @@ namespace SqlSugar //} //else //{ - result = Synchronization(); + result = Synchronization(); //} ///Because SqlSugarScope implements thread safety //else if (IsSingleInstanceAsync()) @@ -1543,7 +1601,7 @@ namespace SqlSugar if (this._AllClients == null) { this._AllClients = new List(); - this._AllClients.Add(new SugarTenant() { ConnectionConfig=this.CurrentConnectionConfig, Context=this.Context }); + this._AllClients.Add(new SugarTenant() { ConnectionConfig = this.CurrentConnectionConfig, Context = this.Context }); } if (_AllClients.HasValue()) { @@ -1555,7 +1613,7 @@ namespace SqlSugar } - private async Task AllClientEachAsync(Func action) + private async Task AllClientEachAsync(Func action) { if (this._AllClients == null) { @@ -1584,19 +1642,19 @@ namespace SqlSugar #region Tenant Crud public ISugarQueryable QueryableWithAttr() { - var result= this.GetConnectionWithAttr().Queryable(); - result.QueryBuilder.IsCrossQueryWithAttr= true; + var result = this.GetConnectionWithAttr().Queryable(); + result.QueryBuilder.IsCrossQueryWithAttr = true; return result; } public IInsertable InsertableWithAttr(T insertObj) where T : class, new() { - var result= this.GetConnectionWithAttr().Insertable(insertObj); + var result = this.GetConnectionWithAttr().Insertable(insertObj); result.InsertBuilder.IsWithAttr = true; return result; } public IInsertable InsertableWithAttr(List insertObjs) where T : class, new() { - var result= this.GetConnectionWithAttr().Insertable(insertObjs); + var result = this.GetConnectionWithAttr().Insertable(insertObjs); result.InsertBuilder.IsWithAttr = true; return result; } diff --git a/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs b/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs index d07d67f43..96329689e 100644 --- a/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs +++ b/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs @@ -921,5 +921,39 @@ namespace SqlSugar { return ScopedContext.GetCurrentConfigIds(); } + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + public void AppendTranSuccessEvent(Action action) + { + ScopedContext.AppendTranSuccessEvent(action); + } + + /// + /// 减少事务成功后事件 + /// + /// + public void SubtractTranSuccessEvent(Action action) + { + ScopedContext.SubtractTranSuccessEvent(action); + } + + /// + /// 清空事务成功后事件 + /// + public void RemoveTranSuccessEvent() + { + ScopedContext.RemoveTranSuccessEvent(); + } + + /// + /// 调用事务成功后事件 + /// + public void InvokeTranSuccessEvent() + { + ScopedContext.InvokeTranSuccessEvent(); + } } } diff --git a/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs b/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs index 496a77d01..7d32cc9d6 100644 --- a/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs +++ b/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs @@ -110,5 +110,23 @@ namespace SqlSugar } return IsCommit; } + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + public void AppendTranSuccessEvent(Action action) + { + this.Tenant.AppendTranSuccessEvent(action); + } + + /// + /// 减少事务成功后事件 + /// + /// + public void SubtractTranSuccessEvent(Action action) + { + this.Tenant.SubtractTranSuccessEvent(action); + } } } From 22448e845602a26904c2ed1d0af21de8309aba1d Mon Sep 17 00:00:00 2001 From: "guoshun.du" Date: Mon, 4 Aug 2025 17:39:37 +0800 Subject: [PATCH 2/2] =?UTF-8?q?*=E4=BA=8B=E5=8A=A1=E6=88=90=E5=8A=9F?= =?UTF-8?q?=E5=90=8E=E4=BA=8B=E4=BB=B6=E5=8A=9F=E8=83=BD=EF=BC=8C=E9=80=9A?= =?UTF-8?q?=E8=BF=87TempItems=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Src/Asp.NetCore2/OracleTest/OracleTest.csproj | 6 +- Src/Asp.NetCore2/OracleTest/Program.cs | 66 ++++++++++++++- .../OracleTest/model/TRFQ_SYS_APILOG.cs | 81 +++++++++++++++++++ .../SugarProvider/SqlSugarProvider.cs | 35 -------- .../SugarProvider/SqlSugarScopeProvider.cs | 33 -------- .../SqlSugar/Interface/ISqlSugarClient.cs | 22 ----- .../SqlSugar/Interface/ITenant.cs | 22 ----- Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs | 42 ++-------- Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs | 34 -------- Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs | 54 ++++++++++--- 10 files changed, 198 insertions(+), 197 deletions(-) create mode 100644 Src/Asp.NetCore2/OracleTest/model/TRFQ_SYS_APILOG.cs diff --git a/Src/Asp.NetCore2/OracleTest/OracleTest.csproj b/Src/Asp.NetCore2/OracleTest/OracleTest.csproj index f796c5008..a05f99280 100644 --- a/Src/Asp.NetCore2/OracleTest/OracleTest.csproj +++ b/Src/Asp.NetCore2/OracleTest/OracleTest.csproj @@ -1,4 +1,4 @@ - + Exe @@ -15,4 +15,8 @@ + + + + diff --git a/Src/Asp.NetCore2/OracleTest/Program.cs b/Src/Asp.NetCore2/OracleTest/Program.cs index e5317df19..eba36e5ef 100644 --- a/Src/Asp.NetCore2/OracleTest/Program.cs +++ b/Src/Asp.NetCore2/OracleTest/Program.cs @@ -1,5 +1,6 @@ using SqlSugar; using System; +using xTPLM.RFQ.Model.XRFQ_APP; namespace OrmTest { @@ -22,6 +23,65 @@ namespace OrmTest _a1_Delete.Init(); _a2_Sql.Init(); _a3_Merge.Init(); + + var DB = DbHelper.GetNewDb(); + + using (var u1 = DB.CreateContext(DB.Ado.IsNoTran())) + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U1事件未完成", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U1事件未完成"); + u1.AppendTranSuccessEvent(edb => + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U1完成事件", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U1完成事件"); + }); + using (var u2 = DB.CreateContext(DB.Ado.IsNoTran())) + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U2事件未完成", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U2事件未完成"); + u2.AppendTranSuccessEvent(edb => + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U2完成事件", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U2完成事件"); + }); + using (var u3 = DB.CreateContext(DB.Ado.IsNoTran())) + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U3事件未完成", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U3事件未完成"); + u3.AppendTranSuccessEvent(edb => + { + DB.Insertable(new TRFQ_SYS_APILOG + { + REQUEST_BODY = "我是U3完成事件", + CREATE_TIME = DateTime.Now, + }).ExecuteCommand(); + Console.WriteLine("我是U3完成事件"); + }); + } + } + + u1.Commit(); + } } } @@ -61,9 +121,9 @@ namespace OrmTest // Logging SQL statements and parameters before execution // 在执行前记录 SQL 语句和参数 it.Aop.OnLogExecuting = (sql, para) => - { - Console.WriteLine(UtilMethods.GetNativeSql(sql, para)); - }; + //{ + // //Console.WriteLine(UtilMethods.GetNativeSql(sql, para)); + //}; }); return db; } diff --git a/Src/Asp.NetCore2/OracleTest/model/TRFQ_SYS_APILOG.cs b/Src/Asp.NetCore2/OracleTest/model/TRFQ_SYS_APILOG.cs new file mode 100644 index 000000000..c436c2255 --- /dev/null +++ b/Src/Asp.NetCore2/OracleTest/model/TRFQ_SYS_APILOG.cs @@ -0,0 +1,81 @@ +using System; +using SqlSugar; + +namespace xTPLM.RFQ.Model.XRFQ_APP +{ + /// + ///接口调用记录 + /// + public partial class TRFQ_SYS_APILOG + { + public TRFQ_SYS_APILOG() + { + + + } + /// + /// Desc:自增主键 + /// Default: + /// Nullable:False + /// + [SugarColumn(IsNullable = false, IsPrimaryKey = true, OracleSequenceName = "TRFQ_SYS_APILOG$SEQ", IsIdentity = true)] + public decimal ID { get; set; } + + /// + /// Desc:接口路径 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 256)] + public string API_URL { get; set; } + + /// + /// Desc:请求类型 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 256)] + public string METHOD { get; set; } + + /// + /// Desc:请求报文 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public string REQUEST_BODY { get; set; } + + /// + /// Desc:应答报文 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public string RESPONSE_BODY { get; set; } + + /// + /// Desc:接口耗时(毫秒) + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? TIME_OUT { get; set; } + + /// + /// Desc:如果发生异常,记录信息 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 2048)] + public string MESSAGE { get; set; } + + /// + /// Desc:交易日期 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? CREATE_TIME { get; set; } + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs index e0a478b68..3d3e27a48 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarProvider.cs @@ -1877,41 +1877,6 @@ namespace SqlSugar await _ThenMapperAsync(pageList, action); }); } - - - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - public void AppendTranSuccessEvent(Action action) - { - Root.AppendTranSuccessEvent(action); - } - - /// - /// 减少事务成功后事件 - /// - /// - public void SubtractTranSuccessEvent(Action action) - { - Root.SubtractTranSuccessEvent(action); - } - - /// - /// 清空事务成功后事件 - /// - public void RemoveTranSuccessEvent() - { - Root.RemoveTranSuccessEvent(); - } - - /// - /// 调用事务成功后事件 - /// - public void InvokeTranSuccessEvent() - { - Root.InvokeTranSuccessEvent(); - } #endregion } } diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs index 1b896d7f9..53bae0919 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs @@ -864,39 +864,6 @@ namespace SqlSugar { ScopedContext.ClearTracking(); } - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - public void AppendTranSuccessEvent(Action action) - { - ScopedContext.AppendTranSuccessEvent(action); - } - - /// - /// 减少事务成功后事件 - /// - /// - public void SubtractTranSuccessEvent(Action action) - { - ScopedContext.SubtractTranSuccessEvent(action); - } - - /// - /// 清空事务成功后事件 - /// - public void RemoveTranSuccessEvent() - { - ScopedContext.RemoveTranSuccessEvent(); - } - - /// - /// 调用事务成功后事件 - /// - public void InvokeTranSuccessEvent() - { - ScopedContext.InvokeTranSuccessEvent(); - } #endregion } } \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs b/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs index 9e008af2c..9f8018302 100644 --- a/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs +++ b/Src/Asp.NetCore2/SqlSugar/Interface/ISqlSugarClient.cs @@ -67,28 +67,6 @@ namespace SqlSugar void Open(); void Close(); ITenant AsTenant(); - - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - void AppendTranSuccessEvent(Action action); - - /// - /// 减少事务成功后事件 - /// - /// - void SubtractTranSuccessEvent(Action action); - - /// - /// 清空事务成功后事件 - /// - void RemoveTranSuccessEvent(); - - /// - /// 调用事务成功后事件 - /// - void InvokeTranSuccessEvent(); #endregion #region Insertable diff --git a/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs b/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs index 82b8a0c8e..8a96ff0ff 100644 --- a/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs +++ b/Src/Asp.NetCore2/SqlSugar/Interface/ITenant.cs @@ -48,27 +48,5 @@ namespace SqlSugar void Close(); void Open(); - - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - void AppendTranSuccessEvent(Action action); - - /// - /// 减少事务成功后事件 - /// - /// - void SubtractTranSuccessEvent(Action action); - - /// - /// 清空事务成功后事件 - /// - void RemoveTranSuccessEvent(); - - /// - /// 调用事务成功后事件 - /// - void InvokeTranSuccessEvent(); } } diff --git a/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs b/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs index e5686793e..6e204080f 100644 --- a/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs +++ b/Src/Asp.NetCore2/SqlSugar/SqlSugarClient.cs @@ -28,10 +28,6 @@ namespace SqlSugar private IgnoreColumnList _IgnoreColumns; private IgnoreColumnList _IgnoreInsertColumns; private Action _configAction; - /// - /// 事务成功事件,当事务提交成功后,触发此事件 - /// - private event Action _TranSuccessEvent; internal Guid? AsyncId { get; set; } internal bool? IsSingleInstance { get; set; } @@ -1301,51 +1297,25 @@ namespace SqlSugar this.Context.InitMappingInfo(typeof(T)); } - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - public void AppendTranSuccessEvent(Action action) - { - _TranSuccessEvent += action; - } - - /// - /// 减少事务成功后事件 - /// - /// - public void SubtractTranSuccessEvent(Action action) - { - _TranSuccessEvent -= action; - } - /// /// 清空事务成功后事件 /// - public void RemoveTranSuccessEvent() + private void RemoveTranSuccessEvent() { - if (_TranSuccessEvent != null) + if (this.TempItems.ContainsKey(SugarUnitOfWork.TranSuccessEvent)) { - //使用取消订阅的方式,这样更为稳妥 - var actionBody = _TranSuccessEvent.GetInvocationList(); - if (actionBody.Length > 0) - { - foreach (Action handler in actionBody) - { - _TranSuccessEvent -= handler; - } - } + this.TempItems.Remove(SugarUnitOfWork.TranSuccessEvent); } } /// /// 调用事务成功后事件 /// - public void InvokeTranSuccessEvent() + private void InvokeTranSuccessEvent() { - if (_TranSuccessEvent != null) + if (this.TempItems.TryGetValue(SugarUnitOfWork.TranSuccessEvent, out object value) && value is Action eventAction) { - _TranSuccessEvent(this); + eventAction(this); } } #endregion diff --git a/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs b/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs index 96329689e..d07d67f43 100644 --- a/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs +++ b/Src/Asp.NetCore2/SqlSugar/SqlSugarScope.cs @@ -921,39 +921,5 @@ namespace SqlSugar { return ScopedContext.GetCurrentConfigIds(); } - - /// - /// 增加事务成功后事件 - /// - /// 需要执行的委托 - public void AppendTranSuccessEvent(Action action) - { - ScopedContext.AppendTranSuccessEvent(action); - } - - /// - /// 减少事务成功后事件 - /// - /// - public void SubtractTranSuccessEvent(Action action) - { - ScopedContext.SubtractTranSuccessEvent(action); - } - - /// - /// 清空事务成功后事件 - /// - public void RemoveTranSuccessEvent() - { - ScopedContext.RemoveTranSuccessEvent(); - } - - /// - /// 调用事务成功后事件 - /// - public void InvokeTranSuccessEvent() - { - ScopedContext.InvokeTranSuccessEvent(); - } } } diff --git a/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs b/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs index 7d32cc9d6..d1d4fd67b 100644 --- a/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs +++ b/Src/Asp.NetCore2/SqlSugar/SugarUnitOfWork.cs @@ -10,7 +10,7 @@ namespace SqlSugar public interface ISugarUnitOfWork where T : SugarUnitOfWork, new() { ISqlSugarClient Db { get; set; } - T CreateContext(bool isTran=true); + T CreateContext(bool isTran = true); } public class SugarUnitOfWork : ISugarUnitOfWork where T : SugarUnitOfWork, new() { @@ -19,7 +19,7 @@ namespace SqlSugar this.Db = db; } public ISqlSugarClient Db { get; set; } - public T CreateContext(bool isTran=true) + public T CreateContext(bool isTran = true) { return Db.CreateContext(isTran); } @@ -36,10 +36,22 @@ namespace SqlSugar /// public interface ISugarUnitOfWork : ISugarUnitOfWorkClear { - ISqlSugarClient Db { get; } - ITenant Tenant { get; } + ISqlSugarClient Db { get; } + ITenant Tenant { get; } SimpleClient GetRepository() where T : class, new(); + + /// + /// 增加事务成功后事件 + /// + /// 需要执行的委托 + void AppendTranSuccessEvent(Action action); + + /// + /// 减少事务成功后事件 + /// + /// + void SubtractTranSuccessEvent(Action action); } /// /// SugarUnitOfWork->ISugarUnitOfWork->ISaugarUnitOfWorkClear @@ -48,6 +60,10 @@ namespace SqlSugar /// public class SugarUnitOfWork : IDisposable, ISugarUnitOfWork { + /// + /// 事务后事件唯一Key + /// + internal const string TranSuccessEvent = "SqlSugar_tranSuccessEvent"; public ISqlSugarClient Db { get; internal set; } public ITenant Tenant { get; internal set; } public bool IsTran { get; internal set; } @@ -61,7 +77,7 @@ namespace SqlSugar { this.Tenant.RollbackTran(); } - if (this.Db.Ado.Transaction==null&&IsClose == false) + if (this.Db.Ado.Transaction == null && IsClose == false) { this.Db.Close(); } @@ -74,13 +90,13 @@ namespace SqlSugar { return new SimpleClient(Db); } - else + else { return new SimpleClient(Db.AsTenant().GetConnection(tenantAttribute.configId)); } } - public RepositoryType GetMyRepository() where RepositoryType:new() + public RepositoryType GetMyRepository() where RepositoryType : new() { var result = (ISugarRepository)new RepositoryType(); var type = typeof(RepositoryType).GetGenericArguments().FirstOrDefault(); @@ -89,7 +105,7 @@ namespace SqlSugar { result.Context = this.Db; } - else + else { result.Context = this.Db.AsTenant().GetConnection(tenantAttribute.configId); } @@ -103,7 +119,7 @@ namespace SqlSugar this.Tenant.CommitTran(); IsCommit = true; } - if (this.Db.Ado.Transaction==null&&this.IsClose == false) + if (this.Db.Ado.Transaction == null && this.IsClose == false) { this.Db.Close(); IsClose = true; @@ -117,7 +133,15 @@ namespace SqlSugar /// 需要执行的委托 public void AppendTranSuccessEvent(Action action) { - this.Tenant.AppendTranSuccessEvent(action); + if (Db.TempItems.TryGetValue(TranSuccessEvent, out object value) && value != null && value is Action eventAction) + { + eventAction += action; + Db.TempItems[TranSuccessEvent] = eventAction; + } + else + { + Db.TempItems[TranSuccessEvent] = action; + } } /// @@ -126,7 +150,15 @@ namespace SqlSugar /// public void SubtractTranSuccessEvent(Action action) { - this.Tenant.SubtractTranSuccessEvent(action); + if (Db.TempItems.TryGetValue(TranSuccessEvent, out object value) && value is Action eventAction) + { + eventAction -= action; + Db.TempItems[TranSuccessEvent] = eventAction; + if (eventAction == null) + { + Db.TempItems.Remove(TranSuccessEvent); + } + } } } }