Pre Merge pull request !84 from 杜子腾/master

This commit is contained in:
杜子腾 2025-08-04 09:39:42 +00:00 committed by Gitee
commit 4cfefc3f14
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
8 changed files with 347 additions and 123 deletions

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@ -15,4 +15,8 @@
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="model\" />
</ItemGroup>
</Project>

View File

@ -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<TRFQ_SYS_APILOG>(new TRFQ_SYS_APILOG
{
REQUEST_BODY = "我是U1事件未完成",
CREATE_TIME = DateTime.Now,
}).ExecuteCommand();
Console.WriteLine("我是U1事件未完成");
u1.AppendTranSuccessEvent(edb =>
{
DB.Insertable<TRFQ_SYS_APILOG>(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<TRFQ_SYS_APILOG>(new TRFQ_SYS_APILOG
{
REQUEST_BODY = "我是U2事件未完成",
CREATE_TIME = DateTime.Now,
}).ExecuteCommand();
Console.WriteLine("我是U2事件未完成");
u2.AppendTranSuccessEvent(edb =>
{
DB.Insertable<TRFQ_SYS_APILOG>(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<TRFQ_SYS_APILOG>(new TRFQ_SYS_APILOG
{
REQUEST_BODY = "我是U3事件未完成",
CREATE_TIME = DateTime.Now,
}).ExecuteCommand();
Console.WriteLine("我是U3事件未完成");
u3.AppendTranSuccessEvent(edb =>
{
DB.Insertable<TRFQ_SYS_APILOG>(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;
}

View File

@ -0,0 +1,81 @@
using System;
using SqlSugar;
namespace xTPLM.RFQ.Model.XRFQ_APP
{
///<summary>
///接口调用记录
///</summary>
public partial class TRFQ_SYS_APILOG
{
public TRFQ_SYS_APILOG()
{
}
/// <summary>
/// Desc:自增主键
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(IsNullable = false, IsPrimaryKey = true, OracleSequenceName = "TRFQ_SYS_APILOG$SEQ", IsIdentity = true)]
public decimal ID { get; set; }
/// <summary>
/// Desc:接口路径
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true, Length = 256)]
public string API_URL { get; set; }
/// <summary>
/// Desc:请求类型
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true, Length = 256)]
public string METHOD { get; set; }
/// <summary>
/// Desc:请求报文
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true)]
public string REQUEST_BODY { get; set; }
/// <summary>
/// Desc:应答报文
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true)]
public string RESPONSE_BODY { get; set; }
/// <summary>
/// Desc:接口耗时(毫秒)
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true)]
public int? TIME_OUT { get; set; }
/// <summary>
/// Desc:如果发生异常,记录信息
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true, Length = 2048)]
public string MESSAGE { get; set; }
/// <summary>
/// Desc:交易日期
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsNullable = true)]
public DateTime? CREATE_TIME { get; set; }
}
}

View File

@ -10,7 +10,7 @@ using System.Threading.Tasks;
namespace SqlSugar
{
public class SqlSugarScopeProvider:ISqlSugarClient
public class SqlSugarScopeProvider : ISqlSugarClient
{
internal SqlSugarProvider conn;
internal string initThreadMainId;

View File

@ -49,10 +49,10 @@ namespace SqlSugar
Task<SugarAsyncLock> AsyncLock(int timeOutSeconds = 30);
DynamicBuilder DynamicBuilder();
void ClearTracking();
void Tracking<T>(T data) where T : class, new();
void Tracking<T>(T data) where T : class, new();
void Tracking<T>(List<T> data) where T : class, new();
SqlSugarClient CopyNew();
T CreateContext<T>(bool isTran=true) where T : SugarUnitOfWork, new();
T CreateContext<T>(bool isTran = true) where T : SugarUnitOfWork, new();
SugarUnitOfWork CreateContext(bool isTran = true);
SplitTableContext SplitHelper(Type entityType);
SplitTableContext SplitHelper<T>() where T : class, new();
@ -143,17 +143,17 @@ namespace SqlSugar
where T4 : class, new();
ISugarQueryable<T> Queryable<T>();
ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable);
ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable,string shortName);
ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable, string shortName);
ISugarQueryable<T> Queryable<T>(string shortName);
#endregion
#region Saveable
GridSaveProvider<T> GridSave<T>(List<T> saveList) where T : class, new();
GridSaveProvider<T> GridSave<T>(List<T> oldList,List<T> saveList) where T : class, new();
GridSaveProvider<T> GridSave<T>(List<T> oldList, List<T> saveList) where T : class, new();
IStorageable<T> Storageable<T>(T[] dataList) where T : class, new();
IStorageable<T> Storageable<T>(IList<T> dataList) where T : class, new();
StorageableDataTable Storageable(List<Dictionary<string, object>> dictionaryList, string tableName);
StorageableDataTable Storageable(Dictionary<string, object> dictionary, string tableName);
StorageableDataTable Storageable(List<Dictionary<string, object>> dictionaryList, string tableName);
StorageableDataTable Storageable(Dictionary<string, object> dictionary, string tableName);
IStorageable<T> Storageable<T>(List<T> dataList) where T : class, new();
IStorageable<T> Storageable<T>(T data) where T : class, new();
StorageableDataTable Storageable(DataTable data);
@ -226,23 +226,23 @@ namespace SqlSugar
#region ThenMapper
void ThenMapper<T>(IEnumerable<T> list, Action<T> action);
Task ThenMapperAsync<T>(IEnumerable<T> list, Func<T,Task> action);
Task ThenMapperAsync<T>(IEnumerable<T> list, Func<T, Task> action);
#endregion
#region Nav CUD
InsertNavTaskInit<T, T> InsertNav<T>(T data) where T : class, new();
InsertNavTaskInit<T, T> InsertNav<T>(List<T> datas) where T : class, new();
InsertNavTaskInit<T, T> InsertNav<T>(T data,InsertNavRootOptions rootOptions) where T : class, new();
InsertNavTaskInit<T, T> InsertNav<T>(T data, InsertNavRootOptions rootOptions) where T : class, new();
InsertNavTaskInit<T, T> InsertNav<T>(List<T> datas, InsertNavRootOptions rootOptions) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(T data) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(List<T> datas) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T,bool>> whereExpression) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T, bool>> whereExpression) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(T data, DeleteNavRootOptions options) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(List<T> datas, DeleteNavRootOptions options) where T : class, new();
DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T, bool>> whereExpression, DeleteNavRootOptions options) where T : class, new();
UpdateNavTaskInit<T, T> UpdateNav<T>(T data) where T : class, new ();
UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas) where T : class, new ();
UpdateNavTaskInit<T, T> UpdateNav<T>(T data,UpdateNavRootOptions rootOptions) where T : class, new();
UpdateNavTaskInit<T, T> UpdateNav<T>(T data) where T : class, new();
UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas) where T : class, new();
UpdateNavTaskInit<T, T> UpdateNav<T>(T data, UpdateNavRootOptions rootOptions) where T : class, new();
UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas, UpdateNavRootOptions rootOptions) where T : class, new();
#endregion

View File

@ -27,6 +27,7 @@ namespace SqlSugar
DbResult<T> UseTran<T>(Func<T> action, Action<Exception> errorCallBack = null);
Task<DbResult<T>> UseTranAsync<T>(Func<Task<T>> action, Action<Exception> errorCallBack = null);
void AddConnection(ConnectionConfig connection);
SqlSugarProvider GetConnection(object configId);
void RemoveConnection(object configId);

View File

@ -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;
@ -49,9 +50,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<SqlSugarClient> configAction)
public SqlSugarClient(ConnectionConfig config, Action<SqlSugarClient> configAction)
{
_configAction=configAction;
_configAction = configAction;
Check.Exception(config == null, "ConnectionConfig config is null");
InitContext(config);
configAction(this);
@ -71,7 +72,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 +88,7 @@ namespace SqlSugar
#region SimpleClient
public T CreateContext<T>(bool isTran=true) where T : SugarUnitOfWork, new()
public T CreateContext<T>(bool isTran = true) where T : SugarUnitOfWork, new()
{
T result = new T();
_CreateContext(isTran, result);
@ -111,7 +112,7 @@ namespace SqlSugar
{
value.GetType().GetProperty("Context").SetValue(value, this);
}
else
else
{
value.GetType().GetProperty("Context").SetValue(value, this.GetConnection(tenantAttribute.configId));
}
@ -124,7 +125,7 @@ namespace SqlSugar
SugarUnitOfWork sugarUnitOf = new SugarUnitOfWork();
return _CreateContext(isTran, sugarUnitOf);
}
private SugarUnitOfWork _CreateContext(bool isTran, SugarUnitOfWork sugarUnitOf)
{
sugarUnitOf.Db = this;
@ -139,7 +140,7 @@ namespace SqlSugar
{
return this.Context.GetSimpleClient<T>();
}
public RepositoryType GetRepository<RepositoryType>() where RepositoryType : ISugarRepository , new()
public RepositoryType GetRepository<RepositoryType>() where RepositoryType : ISugarRepository, new()
{
Type type = typeof(RepositoryType);
var isAnyParamter = type.GetConstructors().Any(z => z.GetParameters().Any());
@ -162,7 +163,7 @@ namespace SqlSugar
#endregion
#region Insertable
public IInsertable<Dictionary<string, object>> InsertableByDynamic(object insertDynamicObject)
public IInsertable<Dictionary<string, object>> InsertableByDynamic(object insertDynamicObject)
{
return this.Context.InsertableByDynamic(insertDynamicObject);
}
@ -177,7 +178,7 @@ namespace SqlSugar
public IInsertable<T> Insertable<T>(dynamic insertDynamicObject) where T : class, new()
{
if (insertDynamicObject is IList<T>)
if (insertDynamicObject is IList<T>)
{
return this.Context.Insertable<T>((insertDynamicObject as IList<T>).ToList());
}
@ -191,8 +192,8 @@ namespace SqlSugar
public IInsertable<T> Insertable<T>(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不支持objectInsertableByObject可以(缺点:功能比较少)");
}
@ -209,9 +210,9 @@ namespace SqlSugar
#region Queryable
#region Nav CUD
public InsertNavTaskInit<T,T> InsertNav<T>(T data) where T : class, new()
public InsertNavTaskInit<T, T> InsertNav<T>(T data) where T : class, new()
{
return this.Context.InsertNav(data);
return this.Context.InsertNav(data);
}
public InsertNavTaskInit<T, T> InsertNav<T>(List<T> datas) where T : class, new()
{
@ -235,7 +236,7 @@ namespace SqlSugar
}
public DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
{
return this.Context.DeleteNav(whereExpression);
return this.Context.DeleteNav(whereExpression);
}
public DeleteNavTaskInit<T, T> DeleteNav<T>(T data, DeleteNavRootOptions options) where T : class, new()
@ -255,13 +256,13 @@ namespace SqlSugar
{
return this.Context.UpdateNav(data);
}
public UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas,UpdateNavRootOptions rootOptions) where T : class, new()
public UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas, UpdateNavRootOptions rootOptions) where T : class, new()
{
return this.Context.UpdateNav(datas, rootOptions);
return this.Context.UpdateNav(datas, rootOptions);
}
public UpdateNavTaskInit<T, T> UpdateNav<T>(T data, UpdateNavRootOptions rootOptions) where T : class, new()
{
return this.Context.UpdateNav(data,rootOptions);
return this.Context.UpdateNav(data, rootOptions);
}
public UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas) where T : class, new()
{
@ -270,34 +271,34 @@ namespace SqlSugar
#endregion
#region Union
public ISugarQueryable<T> Union<T>(List<ISugarQueryable<T>> queryables) where T : class
public ISugarQueryable<T> Union<T>(List<ISugarQueryable<T>> queryables) where T : class
{
return this.Context.Union(queryables);
}
public ISugarQueryable<T> Union<T>(params ISugarQueryable<T>[] queryables) where T : class
public ISugarQueryable<T> Union<T>(params ISugarQueryable<T>[] queryables) where T : class
{
return this.Context.Union(queryables);
}
public ISugarQueryable<T> UnionAll<T>(List<ISugarQueryable<T>> queryables) where T : class
public ISugarQueryable<T> UnionAll<T>(List<ISugarQueryable<T>> queryables) where T : class
{
return this.Context.UnionAll(queryables);
}
public ISugarQueryable<T> UnionAll<T>(params ISugarQueryable<T>[] queryables) where T : class
public ISugarQueryable<T> UnionAll<T>(params ISugarQueryable<T>[] 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<T> MasterQueryable<T>()
{
@ -505,16 +506,16 @@ namespace SqlSugar
{
return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinType1, joinExpression1, joinType2, joinExpression2).With(SqlWith.Null);
}
public ISugarQueryable<T, T2, T3,T4> Queryable<T, T2, T3, T4>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, ISugarQueryable<T3> joinQueryable3, ISugarQueryable<T4> joinQueryable4,
JoinType joinType1, Expression<Func<T, T2, T3,T4, bool>> joinExpression1,
public ISugarQueryable<T, T2, T3, T4> Queryable<T, T2, T3, T4>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, ISugarQueryable<T3> joinQueryable3, ISugarQueryable<T4> joinQueryable4,
JoinType joinType1, Expression<Func<T, T2, T3, T4, bool>> joinExpression1,
JoinType joinType2, Expression<Func<T, T2, T3, T4, bool>> joinExpression2,
JoinType joinType3, Expression<Func<T, T2, T3, T4, bool>> 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<T> Queryable<T>()
@ -522,20 +523,20 @@ namespace SqlSugar
return this.Context.Queryable<T>();
}
public ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable)
public ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable)
{
var result= this.Context.Queryable<T>(queryable);
var result = this.Context.Queryable<T>(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<T> Queryable<T>(ISugarQueryable<T> queryable,string shortName)
{
return this.Context.Queryable(queryable,shortName);
public ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable, string shortName)
{
return this.Context.Queryable(queryable, shortName);
}
public ISugarQueryable<T> Queryable<T>(string shortName)
@ -548,7 +549,7 @@ namespace SqlSugar
#region Saveable
public GridSaveProvider<T> GridSave<T>(List<T> saveList) where T : class, new()
{
return this.Context.GridSave(saveList);
return this.Context.GridSave(saveList);
}
public GridSaveProvider<T> GridSave<T>(List<T> oldList, List<T> saveList) where T : class, new()
{
@ -558,7 +559,7 @@ namespace SqlSugar
{
return this.Context.Storageable(data);
}
public StorageableDataTable Storageable(List<Dictionary<string,object>> dictionaryList,string tableName)
public StorageableDataTable Storageable(List<Dictionary<string, object>> dictionaryList, string tableName)
{
DataTable dt = this.Context.Utilities.DictionaryListToDataTable(dictionaryList);
dt.TableName = tableName;
@ -586,7 +587,7 @@ namespace SqlSugar
public IStorageable<T> Storageable<T>(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<T> { data});
return this.Context.Storageable(new List<T> { data });
}
[Obsolete("use Storageable")]
@ -606,17 +607,17 @@ namespace SqlSugar
#endregion
#region Reportable
public IReportable<T> Reportable<T>(T data)
public IReportable<T> Reportable<T>(T data)
{
return this.Context.Reportable(data);
}
public IReportable<T> Reportable<T>(List<T> list)
public IReportable<T> Reportable<T>(List<T> list)
{
return this.Context.Reportable(list);
}
public IReportable<T> Reportable<T>(T [] array)
public IReportable<T> Reportable<T>(T[] array)
{
return this.Context.Reportable(array);
return this.Context.Reportable(array);
}
#endregion
@ -742,7 +743,7 @@ namespace SqlSugar
public IUpdateable<T> Updateable<T>(dynamic updateDynamicObject) where T : class, new()
{
if (updateDynamicObject is IList<T>)
if (updateDynamicObject is IList<T>)
{
return this.Context.Updateable<T>((updateDynamicObject as IList<T>).ToList());
}
@ -836,16 +837,16 @@ namespace SqlSugar
{
this.Context.ThenMapper(list, action);
}
public Task ThenMapperAsync<T>(IEnumerable<T> list, Func<T, Task> action)
public Task ThenMapperAsync<T>(IEnumerable<T> list, Func<T, Task> 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 +860,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 +907,7 @@ namespace SqlSugar
});
}
}
public SqlSugarProvider GetConnectionWithAttr<T>()
public SqlSugarProvider GetConnectionWithAttr<T>()
{
var attr = typeof(T).GetCustomAttribute<TenantAttribute>();
if (attr == null)
@ -933,17 +934,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 +953,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 +970,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<ConnectionConfig, bool> changeExpression)
@ -1004,7 +1005,7 @@ namespace SqlSugar
_IsAllTran = true;
AllClientEach(it => it.Ado.BeginTran());
}
public void BeginTran(IsolationLevel iso)
{
_IsAllTran = true;
@ -1016,7 +1017,7 @@ namespace SqlSugar
_IsAllTran = true;
await AllClientEachAsync(async it => await it.Ado.BeginTranAsync());
}
public async Task BeginTranAsync(IsolationLevel iso)
{
_IsAllTran = true;
@ -1033,13 +1034,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 +1062,8 @@ namespace SqlSugar
});
_IsAllTran = false;
this.InvokeTranSuccessEvent();
this.RemoveTranSuccessEvent();
}
public DbResult<bool> UseTran(Action action, Action<Exception> errorCallBack = null)
{
@ -1141,7 +1146,7 @@ namespace SqlSugar
try
{
this.BeginTran();
T data=default(T);
T data = default(T);
if (action != null)
data = await action();
this.CommitTran();
@ -1165,14 +1170,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 +1222,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 +1239,46 @@ namespace SqlSugar
{
return this.Context.DynamicBuilder();
}
public void Tracking<T>(T data) where T : class, new()
public void Tracking<T>(T data) where T : class, new()
{
this.Context.Tracking(data);
}
public void ClearTracking()
public void ClearTracking()
{
this.Context.ClearTracking();
}
public void Tracking<T>(List<T> datas) where T : class, new()
public void Tracking<T>(List<T> 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<ConnectionConfig> connections = new List<ConnectionConfig>();
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 +1296,28 @@ namespace SqlSugar
{
this.Context.InitMappingInfo(typeof(T));
}
/// <summary>
/// 清空事务成功后事件
/// </summary>
private void RemoveTranSuccessEvent()
{
if (this.TempItems.ContainsKey(SugarUnitOfWork.TranSuccessEvent))
{
this.TempItems.Remove(SugarUnitOfWork.TranSuccessEvent);
}
}
/// <summary>
/// 调用事务成功后事件
/// </summary>
private void InvokeTranSuccessEvent()
{
if (this.TempItems.TryGetValue(SugarUnitOfWork.TranSuccessEvent, out object value) && value is Action<ISqlSugarClient> eventAction)
{
eventAction(this);
}
}
#endregion
#region Helper
@ -1297,11 +1325,11 @@ namespace SqlSugar
{
return this.Context.AsyncLock(timeOutSeconds);
}
public SplitTableContext SplitHelper<T>() where T:class,new()
public SplitTableContext SplitHelper<T>() where T : class, new()
{
return this.Context.SplitHelper<T>();
}
public SplitTableContext SplitHelper(Type entityType)
public SplitTableContext SplitHelper(Type entityType)
{
return this.Context.SplitHelper(entityType);
}
@ -1326,7 +1354,7 @@ namespace SqlSugar
//}
//else
//{
result = Synchronization();
result = Synchronization();
//}
///Because SqlSugarScope implements thread safety
//else if (IsSingleInstanceAsync())
@ -1543,7 +1571,7 @@ namespace SqlSugar
if (this._AllClients == null)
{
this._AllClients = new List<SugarTenant>();
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 +1583,7 @@ namespace SqlSugar
}
private async Task AllClientEachAsync(Func<ISqlSugarClient,Task> action)
private async Task AllClientEachAsync(Func<ISqlSugarClient, Task> action)
{
if (this._AllClients == null)
{
@ -1584,19 +1612,19 @@ namespace SqlSugar
#region Tenant Crud
public ISugarQueryable<T> QueryableWithAttr<T>()
{
var result= this.GetConnectionWithAttr<T>().Queryable<T>();
result.QueryBuilder.IsCrossQueryWithAttr= true;
var result = this.GetConnectionWithAttr<T>().Queryable<T>();
result.QueryBuilder.IsCrossQueryWithAttr = true;
return result;
}
public IInsertable<T> InsertableWithAttr<T>(T insertObj) where T : class, new()
{
var result= this.GetConnectionWithAttr<T>().Insertable(insertObj);
var result = this.GetConnectionWithAttr<T>().Insertable(insertObj);
result.InsertBuilder.IsWithAttr = true;
return result;
}
public IInsertable<T> InsertableWithAttr<T>(List<T> insertObjs) where T : class, new()
{
var result= this.GetConnectionWithAttr<T>().Insertable(insertObjs);
var result = this.GetConnectionWithAttr<T>().Insertable(insertObjs);
result.InsertBuilder.IsWithAttr = true;
return result;
}

View File

@ -10,7 +10,7 @@ namespace SqlSugar
public interface ISugarUnitOfWork<T> where T : SugarUnitOfWork, new()
{
ISqlSugarClient Db { get; set; }
T CreateContext(bool isTran=true);
T CreateContext(bool isTran = true);
}
public class SugarUnitOfWork<T> : ISugarUnitOfWork<T> 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<T>(isTran);
}
@ -36,10 +36,22 @@ namespace SqlSugar
/// </summary>
public interface ISugarUnitOfWork : ISugarUnitOfWorkClear
{
ISqlSugarClient Db { get; }
ITenant Tenant { get; }
ISqlSugarClient Db { get; }
ITenant Tenant { get; }
SimpleClient<T> GetRepository<T>() where T : class, new();
/// <summary>
/// 增加事务成功后事件
/// </summary>
/// <param name="action">需要执行的委托</param>
void AppendTranSuccessEvent(Action<ISqlSugarClient> action);
/// <summary>
/// 减少事务成功后事件
/// </summary>
/// <param name="action"></param>
void SubtractTranSuccessEvent(Action<ISqlSugarClient> action);
}
/// <summary>
/// SugarUnitOfWork->ISugarUnitOfWork->ISaugarUnitOfWorkClear
@ -48,6 +60,10 @@ namespace SqlSugar
/// </summary>
public class SugarUnitOfWork : IDisposable, ISugarUnitOfWork
{
/// <summary>
/// 事务后事件唯一Key
/// </summary>
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<T>(Db);
}
else
else
{
return new SimpleClient<T>(Db.AsTenant().GetConnection(tenantAttribute.configId));
}
}
public RepositoryType GetMyRepository<RepositoryType>() where RepositoryType:new()
public RepositoryType GetMyRepository<RepositoryType>() 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,12 +119,46 @@ 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;
}
return IsCommit;
}
/// <summary>
/// 增加事务成功后事件
/// </summary>
/// <param name="action">需要执行的委托</param>
public void AppendTranSuccessEvent(Action<ISqlSugarClient> action)
{
if (Db.TempItems.TryGetValue(TranSuccessEvent, out object value) && value != null && value is Action<ISqlSugarClient> eventAction)
{
eventAction += action;
Db.TempItems[TranSuccessEvent] = eventAction;
}
else
{
Db.TempItems[TranSuccessEvent] = action;
}
}
/// <summary>
/// 减少事务成功后事件
/// </summary>
/// <param name="action"></param>
public void SubtractTranSuccessEvent(Action<ISqlSugarClient> action)
{
if (Db.TempItems.TryGetValue(TranSuccessEvent, out object value) && value is Action<ISqlSugarClient> eventAction)
{
eventAction -= action;
Db.TempItems[TranSuccessEvent] = eventAction;
if (eventAction == null)
{
Db.TempItems.Remove(TranSuccessEvent);
}
}
}
}
}