SqlSugarClient.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.Dynamic;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace SqlSugar
  13. {
  14. public partial class SqlSugarClient : ISqlSugarClient, ITenant
  15. {
  16. #region Gobal Property
  17. private SqlSugarProvider _Context = null;
  18. private string _ThreadId;
  19. private ConnectionConfig _CurrentConnectionConfig;
  20. internal List<SugarTenant> _AllClients;
  21. private bool _IsAllTran = false;
  22. private bool _IsOpen = false;
  23. private MappingTableList _MappingTables;
  24. private MappingColumnList _MappingColumns;
  25. private IgnoreColumnList _IgnoreColumns;
  26. private IgnoreColumnList _IgnoreInsertColumns;
  27. internal Guid? AsyncId { get; set; }
  28. internal bool? IsSingleInstance { get; set; }
  29. #endregion
  30. #region Constructor
  31. public SqlSugarClient(ConnectionConfig config)
  32. {
  33. Check.Exception(config == null, "ConnectionConfig config is null");
  34. InitContext(config);
  35. }
  36. public SqlSugarClient(List<ConnectionConfig> configs)
  37. {
  38. Check.Exception(configs.IsNullOrEmpty(), "List<ConnectionConfig> configs is null or count=0");
  39. InitConfigs(configs);
  40. var config = configs.First();
  41. InitContext(config);
  42. _AllClients = configs.Select(it => new SugarTenant() { ConnectionConfig = it }).ToList(); ;
  43. _AllClients.First(it => it.ConnectionConfig.ConfigId == config.ConfigId).Context = this.Context;
  44. }
  45. public SqlSugarClient(ConnectionConfig config ,Action<SqlSugarClient> configAction)
  46. {
  47. Check.Exception(config == null, "ConnectionConfig config is null");
  48. InitContext(config);
  49. configAction(this);
  50. }
  51. public SqlSugarClient(List<ConnectionConfig> configs, Action<SqlSugarClient> configAction)
  52. {
  53. Check.Exception(configs.IsNullOrEmpty(), "List<ConnectionConfig> configs is null or count=0");
  54. InitConfigs(configs);
  55. var config = configs.First();
  56. InitContext(config);
  57. _AllClients = configs.Select(it => new SugarTenant() { ConnectionConfig = it }).ToList(); ;
  58. _AllClients.First(it => it.ConnectionConfig.ConfigId == config.ConfigId).Context = this.Context;
  59. configAction(this);
  60. }
  61. #endregion
  62. #region Global variable
  63. public SugarActionType SugarActionType { get { return this.Context.SugarActionType; }set { this.Context.SugarActionType = value; } }
  64. public SqlSugarProvider Context { get { return GetContext(); } }
  65. public bool IsSystemTablesConfig => this.Context.IsSystemTablesConfig;
  66. public ConnectionConfig CurrentConnectionConfig { get { return _CurrentConnectionConfig; } set { _CurrentConnectionConfig = value; } }
  67. public Guid ContextID { get { return this.Context.ContextID; } set { this.Context.ContextID = value; } }
  68. public ConfigQuery ConfigQuery { get { return this.Context.ConfigQuery; } set { this.Context.ConfigQuery = value; } }
  69. public MappingTableList MappingTables { get { return _MappingTables; } set { _MappingTables = value; } }
  70. public MappingColumnList MappingColumns { get { return _MappingColumns; } set { _MappingColumns = value; } }
  71. public IgnoreColumnList IgnoreColumns { get { return _IgnoreColumns; } set { _IgnoreColumns = value; } }
  72. public IgnoreColumnList IgnoreInsertColumns { get { return _IgnoreInsertColumns; } set { _IgnoreInsertColumns = value; } }
  73. public Dictionary<string, object> TempItems { get { return this.Context.TempItems; } set { this.Context.TempItems = value; } }
  74. #endregion
  75. #region SimpleClient
  76. public T CreateContext<T>(bool isTran=true) where T : SugarUnitOfWork, new()
  77. {
  78. T result = new T();
  79. _CreateContext(isTran, result);
  80. var type = typeof(T);
  81. var ps = type.GetProperties();
  82. var cacheKey = "SugarUnitOfWork" + typeof(T).FullName + typeof(T).GetHashCode();
  83. var properies = new ReflectionInoCacheService().GetOrCreate(cacheKey,
  84. () =>
  85. ps.Where(it =>
  86. (it.PropertyType.BaseType != null && it.PropertyType.BaseType.Name.StartsWith("SimpleClient`"))
  87. ||
  88. it.PropertyType.Name.StartsWith("SimpleClient`")
  89. ));
  90. foreach (var item in properies)
  91. {
  92. var value = Activator.CreateInstance(item.PropertyType);
  93. TenantAttribute tenantAttribute = item.PropertyType.GetGenericArguments()[0].GetCustomAttribute<TenantAttribute>();
  94. if (tenantAttribute == null)
  95. {
  96. value.GetType().GetProperty("Context").SetValue(value, this);
  97. }
  98. else
  99. {
  100. value.GetType().GetProperty("Context").SetValue(value, this.GetConnection(tenantAttribute.configId));
  101. }
  102. item.SetValue(result, value);
  103. }
  104. return result;
  105. }
  106. public SugarUnitOfWork CreateContext(bool isTran = true)
  107. {
  108. SugarUnitOfWork sugarUnitOf = new SugarUnitOfWork();
  109. return _CreateContext(isTran, sugarUnitOf);
  110. }
  111. private SugarUnitOfWork _CreateContext(bool isTran, SugarUnitOfWork sugarUnitOf)
  112. {
  113. sugarUnitOf.Db = this;
  114. sugarUnitOf.Tenant = this;
  115. sugarUnitOf.IsTran = isTran;
  116. this.Open();
  117. if (isTran)
  118. this.BeginTran();
  119. return sugarUnitOf;
  120. }
  121. public SimpleClient<T> GetSimpleClient<T>() where T : class, new()
  122. {
  123. return this.Context.GetSimpleClient<T>();
  124. }
  125. public RepositoryType GetRepository<RepositoryType>() where RepositoryType : ISugarRepository , new()
  126. {
  127. Type type = typeof(RepositoryType);
  128. var isAnyParamter = type.GetConstructors().Any(z => z.GetParameters().Any());
  129. object o = null;
  130. if (isAnyParamter)
  131. {
  132. o = Activator.CreateInstance(type, new string[] { null });
  133. }
  134. else
  135. {
  136. o = Activator.CreateInstance(type);
  137. }
  138. var result = (RepositoryType)o;
  139. if (result.Context == null)
  140. {
  141. result.Context = this.Context;
  142. }
  143. return result;
  144. }
  145. #endregion
  146. #region Insertable
  147. public IInsertable<Dictionary<string, object>> InsertableByDynamic(object insertDynamicObject)
  148. {
  149. return this.Context.InsertableByDynamic(insertDynamicObject);
  150. }
  151. public InsertMethodInfo InsertableByObject(object singleEntityObjectOrListObject)
  152. {
  153. return this.Context.InsertableByObject(singleEntityObjectOrListObject);
  154. }
  155. public IInsertable<T> Insertable<T>(Dictionary<string, object> columnDictionary) where T : class, new()
  156. {
  157. return this.Context.Insertable<T>(columnDictionary);
  158. }
  159. public IInsertable<T> Insertable<T>(dynamic insertDynamicObject) where T : class, new()
  160. {
  161. if (insertDynamicObject is IList<T>)
  162. {
  163. return this.Context.Insertable<T>((insertDynamicObject as IList<T>).ToList());
  164. }
  165. return this.Context.Insertable<T>(insertDynamicObject);
  166. }
  167. public IInsertable<T> Insertable<T>(List<T> insertObjs) where T : class, new()
  168. {
  169. return this.Context.Insertable<T>(insertObjs);
  170. }
  171. public IInsertable<T> Insertable<T>(T insertObj) where T : class, new()
  172. {
  173. Check.ExceptionEasy(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() ","需要Class,new()约束,并且类属性中不能有required修饰符");
  174. if (typeof(T).Name == "Object")
  175. {
  176. Check.ExceptionEasy("Object type use db.InsertableByObject(obj).ExecuteCommand()", "检测到T为Object类型,请使用 db.InsertableByObject(obj).ExecuteCommand(),Insertable不支持object,InsertableByObject可以(缺点:功能比较少)");
  177. }
  178. return this.Context.Insertable<T>(insertObj);
  179. }
  180. public IInsertable<T> Insertable<T>(T[] insertObjs) where T : class, new()
  181. {
  182. return this.Context.Insertable<T>(insertObjs);
  183. }
  184. #endregion
  185. #region Queryable
  186. #region Nav CUD
  187. public InsertNavTaskInit<T,T> InsertNav<T>(T data) where T : class, new()
  188. {
  189. return this.Context.InsertNav(data);
  190. }
  191. public InsertNavTaskInit<T, T> InsertNav<T>(List<T> datas) where T : class, new()
  192. {
  193. return this.Context.InsertNav(datas);
  194. }
  195. public InsertNavTaskInit<T, T> InsertNav<T>(T data, InsertNavRootOptions rootOptions) where T : class, new()
  196. {
  197. return this.Context.InsertNav(data, rootOptions);
  198. }
  199. public InsertNavTaskInit<T, T> InsertNav<T>(List<T> datas, InsertNavRootOptions rootOptions) where T : class, new()
  200. {
  201. return this.Context.InsertNav(datas, rootOptions);
  202. }
  203. public DeleteNavTaskInit<T, T> DeleteNav<T>(T data) where T : class, new()
  204. {
  205. return this.Context.DeleteNav(data);
  206. }
  207. public DeleteNavTaskInit<T, T> DeleteNav<T>(List<T> datas) where T : class, new()
  208. {
  209. return this.Context.DeleteNav(datas);
  210. }
  211. public DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
  212. {
  213. return this.Context.DeleteNav(whereExpression);
  214. }
  215. public DeleteNavTaskInit<T, T> DeleteNav<T>(T data, DeleteNavRootOptions options) where T : class, new()
  216. {
  217. return this.Context.DeleteNav(data, options);
  218. }
  219. public DeleteNavTaskInit<T, T> DeleteNav<T>(List<T> datas, DeleteNavRootOptions options) where T : class, new()
  220. {
  221. return this.Context.DeleteNav(datas, options);
  222. }
  223. public DeleteNavTaskInit<T, T> DeleteNav<T>(Expression<Func<T, bool>> whereExpression, DeleteNavRootOptions options) where T : class, new()
  224. {
  225. return this.Context.DeleteNav(whereExpression, options);
  226. }
  227. public UpdateNavTaskInit<T, T> UpdateNav<T>(T data) where T : class, new()
  228. {
  229. return this.Context.UpdateNav(data);
  230. }
  231. public UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas,UpdateNavRootOptions rootOptions) where T : class, new()
  232. {
  233. return this.Context.UpdateNav(datas, rootOptions);
  234. }
  235. public UpdateNavTaskInit<T, T> UpdateNav<T>(T data, UpdateNavRootOptions rootOptions) where T : class, new()
  236. {
  237. return this.Context.UpdateNav(data,rootOptions);
  238. }
  239. public UpdateNavTaskInit<T, T> UpdateNav<T>(List<T> datas) where T : class, new()
  240. {
  241. return this.Context.UpdateNav(datas);
  242. }
  243. #endregion
  244. #region Union
  245. public ISugarQueryable<T> Union<T>(List<ISugarQueryable<T>> queryables) where T : class, new()
  246. {
  247. return this.Context.Union(queryables);
  248. }
  249. public ISugarQueryable<T> Union<T>(params ISugarQueryable<T>[] queryables) where T : class, new()
  250. {
  251. return this.Context.Union(queryables);
  252. }
  253. public ISugarQueryable<T> UnionAll<T>(List<ISugarQueryable<T>> queryables) where T : class, new()
  254. {
  255. return this.Context.UnionAll(queryables);
  256. }
  257. public ISugarQueryable<T> UnionAll<T>(params ISugarQueryable<T>[] queryables) where T : class, new()
  258. {
  259. return this.Context.UnionAll(queryables);
  260. }
  261. #endregion
  262. public QueryMethodInfo QueryableByObject(Type entityType)
  263. {
  264. return this.Context.QueryableByObject(entityType);
  265. }
  266. public QueryMethodInfo QueryableByObject(Type entityType,string shortName)
  267. {
  268. return this.Context.QueryableByObject(entityType,shortName);
  269. }
  270. public ISugarQueryable<T> MasterQueryable<T>()
  271. {
  272. return this.Context.MasterQueryable<T>();
  273. }
  274. public ISugarQueryable<T> SlaveQueryable<T>()
  275. {
  276. return this.Context.SlaveQueryable<T>();
  277. }
  278. public ISugarQueryable<T> SqlQueryable<T>(string sql) where T : class, new()
  279. {
  280. return this.Context.SqlQueryable<T>(sql);
  281. }
  282. public ISugarQueryable<ExpandoObject> Queryable(string tableName, string shortName)
  283. {
  284. return this.Context.Queryable(tableName, shortName);
  285. }
  286. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, bool>> joinExpression) where T : class, new()
  287. {
  288. return this.Context.Queryable(joinExpression);
  289. }
  290. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, JoinQueryInfos>> joinExpression)
  291. {
  292. return this.Context.Queryable(joinExpression);
  293. }
  294. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, object[]>> joinExpression)
  295. {
  296. return this.Context.Queryable(joinExpression);
  297. }
  298. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, bool>> joinExpression) where T : class, new()
  299. {
  300. return this.Context.Queryable(joinExpression);
  301. }
  302. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, JoinQueryInfos>> joinExpression)
  303. {
  304. return this.Context.Queryable(joinExpression);
  305. }
  306. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, object[]>> joinExpression)
  307. {
  308. return this.Context.Queryable(joinExpression);
  309. }
  310. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, bool>> joinExpression) where T : class, new()
  311. {
  312. return this.Context.Queryable(joinExpression);
  313. }
  314. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, JoinQueryInfos>> joinExpression)
  315. {
  316. return this.Context.Queryable(joinExpression);
  317. }
  318. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, object[]>> joinExpression)
  319. {
  320. return this.Context.Queryable(joinExpression);
  321. }
  322. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, bool>> joinExpression) where T : class, new()
  323. {
  324. return this.Context.Queryable(joinExpression);
  325. }
  326. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, JoinQueryInfos>> joinExpression)
  327. {
  328. return this.Context.Queryable(joinExpression);
  329. }
  330. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> Queryable<T, T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, object[]>> joinExpression)
  331. {
  332. return this.Context.Queryable(joinExpression);
  333. }
  334. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8> Queryable<T, T2, T3, T4, T5, T6, T7, T8>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, bool>> joinExpression) where T : class, new()
  335. {
  336. return this.Context.Queryable(joinExpression);
  337. }
  338. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8> Queryable<T, T2, T3, T4, T5, T6, T7, T8>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, JoinQueryInfos>> joinExpression)
  339. {
  340. return this.Context.Queryable(joinExpression);
  341. }
  342. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7, T8> Queryable<T, T2, T3, T4, T5, T6, T7, T8>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, object[]>> joinExpression)
  343. {
  344. return this.Context.Queryable(joinExpression);
  345. }
  346. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7> Queryable<T, T2, T3, T4, T5, T6, T7>(Expression<Func<T, T2, T3, T4, T5, T6, T7, bool>> joinExpression) where T : class, new()
  347. {
  348. return this.Context.Queryable(joinExpression);
  349. }
  350. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7> Queryable<T, T2, T3, T4, T5, T6, T7>(Expression<Func<T, T2, T3, T4, T5, T6, T7, JoinQueryInfos>> joinExpression)
  351. {
  352. return this.Context.Queryable(joinExpression);
  353. }
  354. public ISugarQueryable<T, T2, T3, T4, T5, T6, T7> Queryable<T, T2, T3, T4, T5, T6, T7>(Expression<Func<T, T2, T3, T4, T5, T6, T7, object[]>> joinExpression)
  355. {
  356. return this.Context.Queryable(joinExpression);
  357. }
  358. public ISugarQueryable<T, T2, T3, T4, T5, T6> Queryable<T, T2, T3, T4, T5, T6>(Expression<Func<T, T2, T3, T4, T5, T6, bool>> joinExpression) where T : class, new()
  359. {
  360. return this.Context.Queryable(joinExpression);
  361. }
  362. public ISugarQueryable<T, T2, T3, T4, T5, T6> Queryable<T, T2, T3, T4, T5, T6>(Expression<Func<T, T2, T3, T4, T5, T6, JoinQueryInfos>> joinExpression)
  363. {
  364. return this.Context.Queryable(joinExpression);
  365. }
  366. public ISugarQueryable<T, T2, T3, T4, T5, T6> Queryable<T, T2, T3, T4, T5, T6>(Expression<Func<T, T2, T3, T4, T5, T6, object[]>> joinExpression)
  367. {
  368. return this.Context.Queryable(joinExpression);
  369. }
  370. public ISugarQueryable<T, T2, T3, T4, T5> Queryable<T, T2, T3, T4, T5>(Expression<Func<T, T2, T3, T4, T5, bool>> joinExpression) where T : class, new()
  371. {
  372. return this.Context.Queryable(joinExpression);
  373. }
  374. public ISugarQueryable<T, T2, T3, T4, T5> Queryable<T, T2, T3, T4, T5>(Expression<Func<T, T2, T3, T4, T5, JoinQueryInfos>> joinExpression)
  375. {
  376. return this.Context.Queryable(joinExpression);
  377. }
  378. public ISugarQueryable<T, T2, T3, T4, T5> Queryable<T, T2, T3, T4, T5>(Expression<Func<T, T2, T3, T4, T5, object[]>> joinExpression)
  379. {
  380. return this.Context.Queryable(joinExpression);
  381. }
  382. public ISugarQueryable<T, T2, T3, T4> Queryable<T, T2, T3, T4>(Expression<Func<T, T2, T3, T4, bool>> joinExpression) where T : class, new()
  383. {
  384. return this.Context.Queryable(joinExpression);
  385. }
  386. public ISugarQueryable<T, T2, T3, T4> Queryable<T, T2, T3, T4>(Expression<Func<T, T2, T3, T4, JoinQueryInfos>> joinExpression)
  387. {
  388. return this.Context.Queryable(joinExpression);
  389. }
  390. public ISugarQueryable<T, T2, T3, T4> Queryable<T, T2, T3, T4>(Expression<Func<T, T2, T3, T4, object[]>> joinExpression)
  391. {
  392. return this.Context.Queryable(joinExpression);
  393. }
  394. public ISugarQueryable<T, T2, T3> Queryable<T, T2, T3>(Expression<Func<T, T2, T3, bool>> joinExpression) where T : class, new()
  395. {
  396. return this.Context.Queryable(joinExpression);
  397. }
  398. public ISugarQueryable<T, T2, T3> Queryable<T, T2, T3>(Expression<Func<T, T2, T3, JoinQueryInfos>> joinExpression)
  399. {
  400. return this.Context.Queryable(joinExpression);
  401. }
  402. public ISugarQueryable<T, T2, T3> Queryable<T, T2, T3>(Expression<Func<T, T2, T3, object[]>> joinExpression)
  403. {
  404. return this.Context.Queryable(joinExpression);
  405. }
  406. public ISugarQueryable<T, T2> Queryable<T, T2>(Expression<Func<T, T2, bool>> joinExpression) where T : class, new()
  407. {
  408. return this.Context.Queryable(joinExpression);
  409. }
  410. public ISugarQueryable<T, T2> Queryable<T, T2>(Expression<Func<T, T2, JoinQueryInfos>> joinExpression)
  411. {
  412. return this.Context.Queryable(joinExpression);
  413. }
  414. public ISugarQueryable<T, T2> Queryable<T, T2>(Expression<Func<T, T2, object[]>> joinExpression)
  415. {
  416. return this.Context.Queryable(joinExpression);
  417. }
  418. public ISugarQueryable<T, T2> Queryable<T, T2>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, Expression<Func<T, T2, bool>> joinExpression)
  419. where T : class, new()
  420. where T2 : class, new()
  421. {
  422. return this.Context.Queryable(joinQueryable1, joinQueryable2, joinExpression).With(SqlWith.Null);
  423. }
  424. public ISugarQueryable<T, T2> Queryable<T, T2>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, JoinType joinType, Expression<Func<T, T2, bool>> joinExpression)
  425. where T : class, new()
  426. where T2 : class, new()
  427. {
  428. return this.Context.Queryable(joinQueryable1, joinQueryable2, joinType, joinExpression).With(SqlWith.Null);
  429. }
  430. public ISugarQueryable<T, T2, T3> Queryable<T, T2, T3>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, ISugarQueryable<T3> joinQueryable3,
  431. JoinType joinType1, Expression<Func<T, T2, T3, bool>> joinExpression1,
  432. JoinType joinType2, Expression<Func<T, T2, T3, bool>> joinExpression2)
  433. where T : class, new()
  434. where T2 : class, new()
  435. where T3 : class, new()
  436. {
  437. return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinType1, joinExpression1, joinType2, joinExpression2).With(SqlWith.Null);
  438. }
  439. public ISugarQueryable<T, T2, T3,T4> Queryable<T, T2, T3, T4>(ISugarQueryable<T> joinQueryable1, ISugarQueryable<T2> joinQueryable2, ISugarQueryable<T3> joinQueryable3, ISugarQueryable<T4> joinQueryable4,
  440. JoinType joinType1, Expression<Func<T, T2, T3,T4, bool>> joinExpression1,
  441. JoinType joinType2, Expression<Func<T, T2, T3, T4, bool>> joinExpression2,
  442. JoinType joinType3, Expression<Func<T, T2, T3, T4, bool>> joinExpression3)
  443. where T : class, new()
  444. where T2 : class, new()
  445. where T3 : class, new()
  446. where T4 : class ,new ()
  447. {
  448. return this.Context.Queryable(joinQueryable1, joinQueryable2, joinQueryable3, joinQueryable4, joinType1, joinExpression1, joinType2, joinExpression2,joinType3, joinExpression3).With(SqlWith.Null);
  449. }
  450. public ISugarQueryable<T> Queryable<T>()
  451. {
  452. return this.Context.Queryable<T>();
  453. }
  454. public ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable)
  455. {
  456. var result= this.Context.Queryable<T>(queryable);
  457. var QueryBuilder = queryable.QueryBuilder;
  458. result.QueryBuilder.IsQueryInQuery = true;
  459. var appendIndex = result.QueryBuilder.Parameters==null?1:result.QueryBuilder.Parameters.Count+1;
  460. result.QueryBuilder.WhereIndex = (QueryBuilder.WhereIndex+1);
  461. result.QueryBuilder.LambdaExpressions.ParameterIndex = (QueryBuilder.LambdaExpressions.ParameterIndex+ appendIndex);
  462. return result;
  463. }
  464. public ISugarQueryable<T> Queryable<T>(ISugarQueryable<T> queryable,string shortName)
  465. {
  466. return this.Context.Queryable(queryable,shortName);
  467. }
  468. public ISugarQueryable<T> Queryable<T>(string shortName)
  469. {
  470. return this.Context.Queryable<T>(shortName);
  471. }
  472. #endregion
  473. #region Saveable
  474. public GridSaveProvider<T> GridSave<T>(List<T> saveList) where T : class, new()
  475. {
  476. return this.Context.GridSave(saveList);
  477. }
  478. public GridSaveProvider<T> GridSave<T>(List<T> oldList, List<T> saveList) where T : class, new()
  479. {
  480. return this.Context.GridSave(oldList, saveList);
  481. }
  482. public StorageableDataTable Storageable(DataTable data)
  483. {
  484. return this.Context.Storageable(data);
  485. }
  486. public StorageableDataTable Storageable(List<Dictionary<string,object>> dictionaryList,string tableName)
  487. {
  488. DataTable dt = this.Context.Utilities.DictionaryListToDataTable(dictionaryList);
  489. dt.TableName = tableName;
  490. return this.Context.Storageable(dt);
  491. }
  492. public StorageableDataTable Storageable(Dictionary<string, object> dictionary, string tableName)
  493. {
  494. DataTable dt = this.Context.Utilities.DictionaryListToDataTable(new List<Dictionary<string, object>>() { dictionary });
  495. dt.TableName = tableName;
  496. return this.Context.Storageable(dt);
  497. }
  498. public IStorageable<T> Storageable<T>(List<T> dataList) where T : class, new()
  499. {
  500. return this.Context.Storageable(dataList);
  501. }
  502. public IStorageable<T> Storageable<T>(IList<T> dataList) where T : class, new()
  503. {
  504. return this.Context.Storageable(dataList.ToList());
  505. }
  506. public IStorageable<T> Storageable<T>(T[] dataList) where T : class, new()
  507. {
  508. return this.Context.Storageable(dataList?.ToList());
  509. }
  510. public IStorageable<T> Storageable<T>(T data) where T : class, new()
  511. {
  512. Check.Exception(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() ");
  513. return this.Context.Storageable(new List<T> { data});
  514. }
  515. [Obsolete("use Storageable")]
  516. public ISaveable<T> Saveable<T>(List<T> saveObjects) where T : class, new()
  517. {
  518. return this.Context.Saveable<T>(saveObjects);
  519. }
  520. [Obsolete("use Storageable")]
  521. public ISaveable<T> Saveable<T>(T saveObject) where T : class, new()
  522. {
  523. return this.Context.Saveable(saveObject);
  524. }
  525. public StorageableMethodInfo StorageableByObject(object singleEntityObjectOrListObject)
  526. {
  527. return this.Context.StorageableByObject(singleEntityObjectOrListObject);
  528. }
  529. #endregion
  530. #region Reportable
  531. public IReportable<T> Reportable<T>(T data)
  532. {
  533. return this.Context.Reportable(data);
  534. }
  535. public IReportable<T> Reportable<T>(List<T> list)
  536. {
  537. return this.Context.Reportable(list);
  538. }
  539. public IReportable<T> Reportable<T>(T [] array)
  540. {
  541. return this.Context.Reportable(array);
  542. }
  543. #endregion
  544. #region Queue
  545. public QueueList Queues { get { return this.Context.Queues; } set { this.Context.Queues = value; } }
  546. public void AddQueue(string sql, object parsmeters = null)
  547. {
  548. this.Context.AddQueue(sql, parsmeters);
  549. }
  550. public void AddQueue(string sql, List<SugarParameter> parsmeters)
  551. {
  552. this.Context.AddQueue(sql, parsmeters);
  553. }
  554. public void AddQueue(string sql, SugarParameter parsmeter)
  555. {
  556. this.Context.AddQueue(sql, parsmeter);
  557. }
  558. public int SaveQueues(bool isTran = true)
  559. {
  560. return this.Context.SaveQueues(isTran);
  561. }
  562. public Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>, List<T6>, List<T7>> SaveQueues<T, T2, T3, T4, T5, T6, T7>(bool isTran = true)
  563. {
  564. return this.Context.SaveQueues<T, T2, T3, T4, T5, T6, T7>(isTran);
  565. }
  566. public Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>, List<T6>> SaveQueues<T, T2, T3, T4, T5, T6>(bool isTran = true)
  567. {
  568. return this.Context.SaveQueues<T, T2, T3, T4, T5, T6>(isTran);
  569. }
  570. public Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>> SaveQueues<T, T2, T3, T4, T5>(bool isTran = true)
  571. {
  572. return this.Context.SaveQueues<T, T2, T3, T4, T5>(isTran);
  573. }
  574. public Tuple<List<T>, List<T2>, List<T3>, List<T4>> SaveQueues<T, T2, T3, T4>(bool isTran = true)
  575. {
  576. return this.Context.SaveQueues<T, T2, T3, T4>(isTran);
  577. }
  578. public Tuple<List<T>, List<T2>, List<T3>> SaveQueues<T, T2, T3>(bool isTran = true)
  579. {
  580. return this.Context.SaveQueues<T, T2, T3>(isTran);
  581. }
  582. public Tuple<List<T>, List<T2>> SaveQueues<T, T2>(bool isTran = true)
  583. {
  584. return this.Context.SaveQueues<T, T2>(isTran);
  585. }
  586. public List<T> SaveQueues<T>(bool isTran = true)
  587. {
  588. return this.Context.SaveQueues<T>(isTran);
  589. }
  590. public Task<int> SaveQueuesAsync(bool isTran = true)
  591. {
  592. return this.Context.SaveQueuesAsync(isTran);
  593. }
  594. public Task<Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>, List<T6>, List<T7>>> SaveQueuesAsync<T, T2, T3, T4, T5, T6, T7>(bool isTran = true)
  595. {
  596. return this.Context.SaveQueuesAsync<T, T2, T3, T4, T5, T6, T7>(isTran);
  597. }
  598. public Task<Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>, List<T6>>> SaveQueuesAsync<T, T2, T3, T4, T5, T6>(bool isTran = true)
  599. {
  600. return this.Context.SaveQueuesAsync<T, T2, T3, T4, T5, T6>(isTran);
  601. }
  602. public Task<Tuple<List<T>, List<T2>, List<T3>, List<T4>, List<T5>>> SaveQueuesAsync<T, T2, T3, T4, T5>(bool isTran = true)
  603. {
  604. return this.Context.SaveQueuesAsync<T, T2, T3, T4, T5>(isTran);
  605. }
  606. public Task<Tuple<List<T>, List<T2>, List<T3>, List<T4>>> SaveQueuesAsync<T, T2, T3, T4>(bool isTran = true)
  607. {
  608. return this.Context.SaveQueuesAsync<T, T2, T3, T4>(isTran);
  609. }
  610. public Task<Tuple<List<T>, List<T2>, List<T3>>> SaveQueuesAsync<T, T2, T3>(bool isTran = true)
  611. {
  612. return this.Context.SaveQueuesAsync<T, T2, T3>(isTran);
  613. }
  614. public Task<Tuple<List<T>, List<T2>>> SaveQueuesAsync<T, T2>(bool isTran = true)
  615. {
  616. return this.Context.SaveQueuesAsync<T, T2>(isTran);
  617. }
  618. public Task<List<T>> SaveQueuesAsync<T>(bool isTran = true)
  619. {
  620. return this.Context.SaveQueuesAsync<T>(isTran);
  621. }
  622. #endregion
  623. #region Updateable
  624. public IUpdateable<Dictionary<string, object>> UpdateableByDynamic(object updateDynamicObject)
  625. {
  626. return this.Context.UpdateableByDynamic(updateDynamicObject);
  627. }
  628. public UpdateMethodInfo UpdateableByObject(object singleEntityObjectOrListObject)
  629. {
  630. return this.Context.UpdateableByObject(singleEntityObjectOrListObject);
  631. }
  632. public UpdateExpressionMethodInfo UpdateableByObject(Type entityType)
  633. {
  634. return this.Context.UpdateableByObject(entityType);
  635. }
  636. public IUpdateable<T> Updateable<T>() where T : class, new()
  637. {
  638. return this.Context.Updateable<T>();
  639. }
  640. public IUpdateable<T> Updateable<T>(Dictionary<string, object> columnDictionary) where T : class, new()
  641. {
  642. return this.Context.Updateable<T>(columnDictionary);
  643. }
  644. public IUpdateable<T> Updateable<T>(dynamic updateDynamicObject) where T : class, new()
  645. {
  646. if (updateDynamicObject is IList<T>)
  647. {
  648. return this.Context.Updateable<T>((updateDynamicObject as IList<T>).ToList());
  649. }
  650. return this.Context.Updateable<T>(updateDynamicObject);
  651. }
  652. public IUpdateable<T> Updateable<T>(Expression<Func<T, bool>> columns) where T : class, new()
  653. {
  654. return this.Context.Updateable<T>(columns);
  655. }
  656. public IUpdateable<T> Updateable<T>(Expression<Func<T, T>> columns) where T : class, new()
  657. {
  658. return this.Context.Updateable<T>(columns);
  659. }
  660. public IUpdateable<T> Updateable<T>(List<T> UpdateObjs) where T : class, new()
  661. {
  662. return this.Context.Updateable<T>(UpdateObjs);
  663. }
  664. public IUpdateable<T> Updateable<T>(T UpdateObj) where T : class, new()
  665. {
  666. return this.Context.Updateable<T>(UpdateObj);
  667. }
  668. public IUpdateable<T> Updateable<T>(T[] UpdateObjs) where T : class, new()
  669. {
  670. return this.Context.Updateable<T>(UpdateObjs);
  671. }
  672. #endregion
  673. #region Ado
  674. public IAdo Ado => this.Context.Ado;
  675. #endregion
  676. #region Deleteable
  677. public DeleteMethodInfo DeleteableByObject(object singleEntityObjectOrListObject)
  678. {
  679. return this.Context.DeleteableByObject(singleEntityObjectOrListObject);
  680. }
  681. public IDeleteable<T> Deleteable<T>() where T : class, new()
  682. {
  683. return this.Context.Deleteable<T>();
  684. }
  685. public IDeleteable<T> Deleteable<T>(dynamic primaryKeyValue) where T : class, new()
  686. {
  687. return this.Context.Deleteable<T>(primaryKeyValue);
  688. }
  689. public IDeleteable<T> Deleteable<T>(dynamic[] primaryKeyValues) where T : class, new()
  690. {
  691. return this.Context.Deleteable<T>(primaryKeyValues);
  692. }
  693. public IDeleteable<T> Deleteable<T>(Expression<Func<T, bool>> expression) where T : class, new()
  694. {
  695. return this.Context.Deleteable(expression);
  696. }
  697. public IDeleteable<T> Deleteable<T>(List<dynamic> pkValue) where T : class, new()
  698. {
  699. return this.Context.Deleteable<T>(pkValue);
  700. }
  701. public IDeleteable<T> Deleteable<T>(List<T> deleteObjs) where T : class, new()
  702. {
  703. return this.Context.Deleteable<T>(deleteObjs);
  704. }
  705. public IDeleteable<T> Deleteable<T>(T deleteObj) where T : class, new()
  706. {
  707. return this.Context.Deleteable<T>(deleteObj);
  708. }
  709. #endregion
  710. #region Fastest
  711. public IFastest<T> Fastest<T>() where T : class, new()
  712. {
  713. return this.Context.Fastest<T>();
  714. }
  715. #endregion
  716. #region ThenMapper
  717. public void ThenMapper<T>(IEnumerable<T> list, Action<T> action)
  718. {
  719. this.Context.ThenMapper(list, action);
  720. }
  721. public Task ThenMapperAsync<T>(IEnumerable<T> list, Func<T, Task> action)
  722. {
  723. return this.Context.ThenMapperAsync(list,action);
  724. }
  725. #endregion
  726. #region More api
  727. public IContextMethods Utilities { get { return this.Context.Utilities; } set { this.Context.Utilities = value; } }
  728. public AopProvider Aop => this.Context.Aop;
  729. public ICodeFirst CodeFirst => this.Context.CodeFirst;
  730. public IDbFirst DbFirst => this.Context.DbFirst;
  731. public IDbMaintenance DbMaintenance => this.Context.DbMaintenance;
  732. public EntityMaintenance EntityMaintenance { get { return this.Context.EntityMaintenance; } set { this.Context.EntityMaintenance = value; } }
  733. public QueryFilterProvider QueryFilter { get { return this.Context.QueryFilter; } set { this.Context.QueryFilter = value; } }
  734. #endregion
  735. #region TenantManager
  736. public ITenant AsTenant()
  737. {
  738. var tenant= this as ITenant;
  739. return tenant;
  740. }
  741. public SqlSugarTransaction UseTran()
  742. {
  743. return new SqlSugarTransaction(this);
  744. }
  745. public void RemoveConnection(dynamic configId)
  746. {
  747. var removeData= this._AllClients.FirstOrDefault(it => ((object)it.ConnectionConfig.ConfigId).ObjToString()== ((object)configId).ObjToString());
  748. object currentId= this.CurrentConnectionConfig.ConfigId;
  749. if (removeData != null)
  750. {
  751. if (removeData.Context.Ado.IsAnyTran())
  752. {
  753. Check.ExceptionEasy("RemoveConnection error has tran",$"删除失败{removeData.ConnectionConfig.ConfigId}存在未提交事务");
  754. }
  755. else if (((object)removeData.ConnectionConfig.ConfigId).ObjToString()== currentId.ObjToString())
  756. {
  757. Check.ExceptionEasy("Default ConfigId cannot be deleted", $"默认库不能删除{removeData.ConnectionConfig.ConfigId}");
  758. }
  759. this._AllClients.Remove(removeData);
  760. }
  761. }
  762. public void AddConnection(ConnectionConfig connection)
  763. {
  764. Check.ArgumentNullException(connection, "AddConnection.connection can't be null");
  765. InitTenant();
  766. var db = this._AllClients.FirstOrDefault(it => ((object)it.ConnectionConfig.ConfigId).ObjToString() == ((object)connection.ConfigId).ObjToString());
  767. if (db == null)
  768. {
  769. if (this._AllClients == null)
  770. {
  771. this._AllClients = new List<SugarTenant>();
  772. }
  773. var provider = new SqlSugarProvider(connection);
  774. if (connection.AopEvents != null)
  775. {
  776. provider.Ado.IsEnableLogEvent = true;
  777. }
  778. this._AllClients.Add(new SugarTenant()
  779. {
  780. ConnectionConfig = connection,
  781. Context = provider
  782. });
  783. }
  784. }
  785. public SqlSugarProvider GetConnectionWithAttr<T>()
  786. {
  787. var attr = typeof(T).GetCustomAttribute<TenantAttribute>();
  788. if (attr == null)
  789. return this.GetConnection(this.CurrentConnectionConfig.ConfigId);
  790. var configId = attr.configId;
  791. return this.GetConnection(configId);
  792. }
  793. public SqlSugarProvider GetConnectionWithAttr(Type type)
  794. {
  795. var attr = type.GetCustomAttribute<TenantAttribute>();
  796. if (attr == null)
  797. return this.GetConnection(this.CurrentConnectionConfig.ConfigId);
  798. var configId = attr.configId;
  799. return this.GetConnection(configId);
  800. }
  801. public SqlSugarScopeProvider GetConnectionScopeWithAttr<T>()
  802. {
  803. var attr = typeof(T).GetCustomAttribute<TenantAttribute>();
  804. if (attr == null)
  805. return this.GetConnectionScope(this.CurrentConnectionConfig.ConfigId);
  806. var configId = attr.configId;
  807. return this.GetConnectionScope(configId);
  808. }
  809. public SqlSugarProvider GetConnection(object configId)
  810. {
  811. InitTenant();
  812. var db = this._AllClients.FirstOrDefault(it =>Convert.ToString(it.ConnectionConfig.ConfigId) ==Convert.ToString(configId));
  813. if (db == null)
  814. {
  815. Check.Exception(true, "ConfigId was not found {0}", configId+"");
  816. }
  817. if (db.Context == null)
  818. {
  819. db.Context = new SqlSugarProvider(db.ConnectionConfig);
  820. }
  821. var intiAop=db.Context.Aop;
  822. if (db.Context.CurrentConnectionConfig.AopEvents == null)
  823. {
  824. db.Context.CurrentConnectionConfig.AopEvents = new AopEvents();
  825. }
  826. if (_IsAllTran && db.Context.Ado.Transaction == null)
  827. {
  828. db.Context.Ado.BeginTran();
  829. }
  830. db.Context.Root = this;
  831. if (db.Context.MappingTables == null)
  832. {
  833. db.Context.MappingTables = new MappingTableList();
  834. }
  835. return db.Context;
  836. }
  837. public SqlSugarScopeProvider GetConnectionScope(object configId)
  838. {
  839. var conn = GetConnection(configId);
  840. return new SqlSugarScopeProvider(conn);
  841. }
  842. public bool IsAnyConnection(object configId)
  843. {
  844. InitTenant();
  845. var db = this._AllClients.FirstOrDefault(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId));
  846. return db != null;
  847. }
  848. public void ChangeDatabase(object configId)
  849. {
  850. configId =Convert.ToString(configId);
  851. var isLog = _Context.Ado.IsEnableLogEvent;
  852. Check.Exception(!_AllClients.Any(it =>Convert.ToString( it.ConnectionConfig.ConfigId) ==Convert.ToString( configId)), "ConfigId was not found {0}", configId+"");
  853. InitTenant(_AllClients.First(it => Convert.ToString(it.ConnectionConfig.ConfigId )==Convert.ToString( configId)));
  854. if (this._IsAllTran)
  855. this.Ado.BeginTran();
  856. if (this._IsOpen)
  857. this.Open();
  858. _Context.Ado.IsEnableLogEvent = isLog;
  859. if (_CurrentConnectionConfig.AopEvents==null)
  860. _CurrentConnectionConfig.AopEvents = new AopEvents();
  861. }
  862. public void ChangeDatabase(Func<ConnectionConfig, bool> changeExpression)
  863. {
  864. var isLog = _Context.Ado.IsEnableLogEvent;
  865. var allConfigs = _AllClients.Select(it => it.ConnectionConfig);
  866. Check.Exception(!allConfigs.Any(changeExpression), "changeExpression was not found {0}", changeExpression.ToString());
  867. InitTenant(_AllClients.First(it => it.ConnectionConfig == allConfigs.First(changeExpression)));
  868. if (this._IsAllTran)
  869. this.Ado.BeginTran();
  870. if (this._IsOpen)
  871. this.Open();
  872. _Context.Ado.IsEnableLogEvent = isLog;
  873. if (_CurrentConnectionConfig.AopEvents == null)
  874. _CurrentConnectionConfig.AopEvents = new AopEvents();
  875. }
  876. public void BeginTran()
  877. {
  878. _IsAllTran = true;
  879. AllClientEach(it => it.Ado.BeginTran());
  880. }
  881. public void BeginTran(IsolationLevel iso)
  882. {
  883. _IsAllTran = true;
  884. AllClientEach(it => it.Ado.BeginTran(iso));
  885. }
  886. public async Task BeginTranAsync()
  887. {
  888. _IsAllTran = true;
  889. await AllClientEachAsync(async it => await it.Ado.BeginTranAsync());
  890. }
  891. public async Task BeginTranAsync(IsolationLevel iso)
  892. {
  893. _IsAllTran = true;
  894. await AllClientEachAsync(async it => await it.Ado.BeginTranAsync(iso));
  895. }
  896. public void CommitTran()
  897. {
  898. this.Context.Ado.CommitTran();
  899. AllClientEach(it =>
  900. {
  901. try
  902. {
  903. it.Ado.CommitTran();
  904. }
  905. catch
  906. {
  907. SugarRetry.Execute(() => it.Ado.CommitTran(), new TimeSpan(0, 0, 5), 3);
  908. }
  909. });
  910. _IsAllTran = false;
  911. }
  912. public async Task CommitTranAsync()
  913. {
  914. await this.Context.Ado.CommitTranAsync();
  915. await AllClientEachAsync(async it =>
  916. {
  917. try
  918. {
  919. await it.Ado.CommitTranAsync();
  920. }
  921. catch
  922. {
  923. SugarRetry.Execute(() => it.Ado.CommitTran(), new TimeSpan(0, 0, 5), 3);
  924. }
  925. });
  926. _IsAllTran = false;
  927. }
  928. public DbResult<bool> UseTran(Action action, Action<Exception> errorCallBack = null)
  929. {
  930. var result = new DbResult<bool>();
  931. try
  932. {
  933. this.BeginTran();
  934. if (action != null)
  935. action();
  936. this.CommitTran();
  937. result.Data = result.IsSuccess = true;
  938. }
  939. catch (Exception ex)
  940. {
  941. result.ErrorException = ex;
  942. result.ErrorMessage = ex.Message;
  943. result.IsSuccess = false;
  944. this.RollbackTran();
  945. if (errorCallBack != null)
  946. {
  947. errorCallBack(ex);
  948. }
  949. }
  950. return result;
  951. }
  952. public async Task<DbResult<bool>> UseTranAsync(Func<Task> action, Action<Exception> errorCallBack = null)
  953. {
  954. var result = new DbResult<bool>();
  955. try
  956. {
  957. await this.BeginTranAsync();
  958. if (action != null)
  959. await action();
  960. await this.CommitTranAsync();
  961. result.Data = result.IsSuccess = true;
  962. }
  963. catch (Exception ex)
  964. {
  965. result.ErrorException = ex;
  966. result.ErrorMessage = ex.Message;
  967. result.IsSuccess = false;
  968. await this.RollbackTranAsync();
  969. if (errorCallBack != null)
  970. {
  971. errorCallBack(ex);
  972. }
  973. }
  974. return result;
  975. }
  976. public DbResult<T> UseTran<T>(Func<T> action, Action<Exception> errorCallBack = null)
  977. {
  978. var result = new DbResult<T>();
  979. try
  980. {
  981. this.BeginTran();
  982. if (action != null)
  983. result.Data = action();
  984. this.CommitTran();
  985. result.IsSuccess = true;
  986. }
  987. catch (Exception ex)
  988. {
  989. result.ErrorException = ex;
  990. result.ErrorMessage = ex.Message;
  991. result.IsSuccess = false;
  992. this.RollbackTran();
  993. if (errorCallBack != null)
  994. {
  995. errorCallBack(ex);
  996. }
  997. }
  998. return result;
  999. }
  1000. public async Task<DbResult<T>> UseTranAsync<T>(Func<Task<T>> action, Action<Exception> errorCallBack = null)
  1001. {
  1002. var result = new DbResult<T>();
  1003. try
  1004. {
  1005. this.BeginTran();
  1006. T data=default(T);
  1007. if (action != null)
  1008. data = await action();
  1009. this.CommitTran();
  1010. result.IsSuccess = true;
  1011. result.Data = data;
  1012. }
  1013. catch (Exception ex)
  1014. {
  1015. result.ErrorException = ex;
  1016. result.ErrorMessage = ex.Message;
  1017. result.IsSuccess = false;
  1018. this.RollbackTran();
  1019. if (errorCallBack != null)
  1020. {
  1021. errorCallBack(ex);
  1022. }
  1023. }
  1024. return result;
  1025. }
  1026. public void RollbackTran()
  1027. {
  1028. this.Context.Ado.RollbackTran();
  1029. AllClientEach(it =>
  1030. {
  1031. try
  1032. {
  1033. it.Ado.RollbackTran();
  1034. }
  1035. catch
  1036. {
  1037. SugarRetry.Execute(() => it.Ado.RollbackTran(), new TimeSpan(0, 0, 5), 3);
  1038. }
  1039. });
  1040. _IsAllTran = false;
  1041. }
  1042. public async Task RollbackTranAsync()
  1043. {
  1044. await this.Context.Ado.RollbackTranAsync();
  1045. await AllClientEachAsync(async it =>
  1046. {
  1047. try
  1048. {
  1049. await it.Ado.RollbackTranAsync();
  1050. }
  1051. catch
  1052. {
  1053. SugarRetry.Execute(() => it.Ado.RollbackTran(), new TimeSpan(0, 0, 5), 3);
  1054. }
  1055. });
  1056. _IsAllTran = false;
  1057. }
  1058. public void Close()
  1059. {
  1060. this.Context.Close();
  1061. AllClientEach(it => it.Close());
  1062. _IsOpen = false;
  1063. }
  1064. public void Open()
  1065. {
  1066. this.Context.Open();
  1067. _IsOpen = true;
  1068. }
  1069. #endregion
  1070. #region IDispose
  1071. public void Dispose()
  1072. {
  1073. AllClientEach(it => it.Ado.RollbackTran());
  1074. AllClientEach(it => it.Dispose());
  1075. }
  1076. #endregion
  1077. #region Cache
  1078. public SugarCacheProvider DataCache
  1079. {
  1080. get { return this.Context.DataCache; }
  1081. }
  1082. #endregion
  1083. #region Other method
  1084. public DynamicBuilder DynamicBuilder()
  1085. {
  1086. return this.Context.DynamicBuilder();
  1087. }
  1088. public void Tracking<T>(T data) where T : class, new()
  1089. {
  1090. this.Context.Tracking(data);
  1091. }
  1092. public void ClearTracking()
  1093. {
  1094. this.Context.ClearTracking();
  1095. }
  1096. public void Tracking<T>(List<T> datas) where T : class, new()
  1097. {
  1098. this.Context.Tracking(datas);
  1099. }
  1100. public SqlSugarClient CopyNew()
  1101. {
  1102. var result= new SqlSugarClient(UtilMethods.CopyConfig(this.Ado.Context.CurrentConnectionConfig));
  1103. result.QueryFilter = this.QueryFilter;
  1104. if (_AllClients != null)
  1105. {
  1106. foreach (var item in _AllClients)
  1107. {
  1108. if (!result.IsAnyConnection(item.ConnectionConfig.ConfigId))
  1109. {
  1110. result.AddConnection(UtilMethods.CopyConfig(item.ConnectionConfig));
  1111. }
  1112. }
  1113. }
  1114. return result;
  1115. }
  1116. public DateTime GetDate()
  1117. {
  1118. return this.Context.GetDate();
  1119. }
  1120. public void InitMappingInfo(Type type)
  1121. {
  1122. this.Context.InitMappingInfo(type);
  1123. }
  1124. public void InitMappingInfo<T>()
  1125. {
  1126. this.Context.InitMappingInfo(typeof(T));
  1127. }
  1128. #endregion
  1129. #region Helper
  1130. public Task<SugarAsyncLock> AsyncLock(int timeOutSeconds = 30)
  1131. {
  1132. return this.Context.AsyncLock(timeOutSeconds);
  1133. }
  1134. public SplitTableContext SplitHelper<T>() where T:class,new()
  1135. {
  1136. return this.Context.SplitHelper<T>();
  1137. }
  1138. public SplitTableContext SplitHelper(Type entityType)
  1139. {
  1140. return this.Context.SplitHelper(entityType);
  1141. }
  1142. public SplitTableContextResult<T> SplitHelper<T>(T data) where T : class, new()
  1143. {
  1144. return this.Context.SplitHelper(data);
  1145. }
  1146. public SplitTableContextResult<T> SplitHelper<T>(List<T> dataList) where T : class, new()
  1147. {
  1148. return this.Context.SplitHelper(dataList);
  1149. }
  1150. private SqlSugarProvider GetContext()
  1151. {
  1152. SqlSugarProvider result = null;
  1153. //if (IsSameThreadAndShard())
  1154. //{
  1155. // result = SameThreadAndShard();
  1156. //}
  1157. //else if (IsNoSameThreadAndShard())
  1158. //{
  1159. // result = NoSameThreadAndShard();
  1160. //}
  1161. //else
  1162. //{
  1163. result = Synchronization();
  1164. //}
  1165. ///Because SqlSugarScope implements thread safety
  1166. //else if (IsSingleInstanceAsync())
  1167. //{
  1168. // result = Synchronization();//Async no support Single Instance
  1169. //}
  1170. //else if (IsAsync())
  1171. //{
  1172. // result = Synchronization();
  1173. //}
  1174. //else
  1175. //{
  1176. // StackTrace st = new StackTrace(true);
  1177. // var methods = st.GetFrames();
  1178. // var isAsync = UtilMethods.IsAnyAsyncMethod(methods);
  1179. // if (isAsync)
  1180. // {
  1181. // result = Synchronization();
  1182. // }
  1183. // else
  1184. // {
  1185. // result = NoSameThread();
  1186. // }
  1187. //}
  1188. if (result.Root == null)
  1189. {
  1190. result.Root = this;
  1191. }
  1192. return result;
  1193. }
  1194. private SqlSugarProvider NoSameThreadAsync()
  1195. {
  1196. var result = GetCallContext();
  1197. return result;
  1198. }
  1199. private SqlSugarProvider NoSameThread()
  1200. {
  1201. if (CallContext.ContextList.Value == null)
  1202. {
  1203. var context = CopyClient();
  1204. AddCallContext(context);
  1205. return context;
  1206. }
  1207. else
  1208. {
  1209. var result = GetCallContext();
  1210. if (result == null)
  1211. {
  1212. var copy = CopyClient();
  1213. AddCallContext(copy);
  1214. return copy;
  1215. }
  1216. else
  1217. {
  1218. return result;
  1219. }
  1220. }
  1221. }
  1222. private void InitTenant()
  1223. {
  1224. if (this._AllClients == null)
  1225. {
  1226. this._AllClients = new List<SugarTenant>();
  1227. this._AllClients.Add(new SugarTenant()
  1228. {
  1229. ConnectionConfig = this.CurrentConnectionConfig,
  1230. Context = this.Context
  1231. });
  1232. }
  1233. }
  1234. private SqlSugarProvider Synchronization()
  1235. {
  1236. _Context.MappingColumns = _MappingColumns;
  1237. _Context.MappingTables = _MappingTables;
  1238. _Context.IgnoreColumns = _IgnoreColumns;
  1239. _Context.IgnoreInsertColumns = _IgnoreInsertColumns;
  1240. return _Context;
  1241. }
  1242. private SqlSugarProvider NoSameThreadAndShard()
  1243. {
  1244. if (CallContext.ContextList.Value.IsNullOrEmpty())
  1245. {
  1246. var copy = CopyClient();
  1247. AddCallContext(copy);
  1248. return copy;
  1249. }
  1250. else
  1251. {
  1252. var result = GetCallContext();
  1253. if (result == null)
  1254. {
  1255. var copy = CopyClient();
  1256. AddCallContext(copy);
  1257. return copy;
  1258. }
  1259. else
  1260. {
  1261. return result;
  1262. }
  1263. }
  1264. }
  1265. private SqlSugarProvider SameThreadAndShard()
  1266. {
  1267. if (CallContext.ContextList.Value.IsNullOrEmpty())
  1268. {
  1269. AddCallContext(_Context);
  1270. return _Context;
  1271. }
  1272. else
  1273. {
  1274. var result = GetCallContext();
  1275. if (result == null)
  1276. {
  1277. var copy = CopyClient();
  1278. AddCallContext(copy);
  1279. return copy;
  1280. }
  1281. else
  1282. {
  1283. return result;
  1284. }
  1285. }
  1286. }
  1287. private bool IsAsync()
  1288. {
  1289. return AsyncId != null;
  1290. }
  1291. private bool IsSingleInstanceAsync()
  1292. {
  1293. return IsSingleInstance == true && AsyncId != null;
  1294. }
  1295. private bool IsSynchronization()
  1296. {
  1297. return _ThreadId == Thread.CurrentThread.ManagedThreadId.ToString();
  1298. }
  1299. //private bool IsNoSameThreadAndShard()
  1300. //{
  1301. // return CurrentConnectionConfig.IsShardSameThread && _ThreadId != Thread.CurrentThread.ManagedThreadId.ToString();
  1302. //}
  1303. //private bool IsSameThreadAndShard()
  1304. //{
  1305. // return CurrentConnectionConfig.IsShardSameThread && _ThreadId == Thread.CurrentThread.ManagedThreadId.ToString();
  1306. //}
  1307. private SqlSugarProvider CopyClient()
  1308. {
  1309. var result = new SqlSugarProvider(this.CurrentConnectionConfig);
  1310. result.MappingColumns = _MappingColumns;
  1311. result.MappingTables = _MappingTables;
  1312. result.IgnoreColumns = _IgnoreColumns;
  1313. result.IgnoreInsertColumns = _IgnoreInsertColumns;
  1314. return result;
  1315. }
  1316. private void AddCallContext(SqlSugarProvider context)
  1317. {
  1318. CallContext.ContextList.Value = new List<SqlSugarProvider>();
  1319. CallContext.ContextList.Value.Add(context);
  1320. }
  1321. private SqlSugarProvider GetCallContext()
  1322. {
  1323. return CallContext.ContextList.Value.FirstOrDefault(it =>
  1324. it.CurrentConnectionConfig.DbType == _Context.CurrentConnectionConfig.DbType &&
  1325. it.CurrentConnectionConfig.ConnectionString == _Context.CurrentConnectionConfig.ConnectionString &&
  1326. it.CurrentConnectionConfig.InitKeyType == _Context.CurrentConnectionConfig.InitKeyType &&
  1327. it.CurrentConnectionConfig.IsAutoCloseConnection == _Context.CurrentConnectionConfig.IsAutoCloseConnection
  1328. );
  1329. }
  1330. protected virtual void InitContext(ConnectionConfig config)
  1331. {
  1332. var aopIsNull = config.AopEvents == null;
  1333. if (aopIsNull)
  1334. {
  1335. config.AopEvents = new AopEvents();
  1336. }
  1337. _Context = new SqlSugarProvider(config);
  1338. if (!aopIsNull)
  1339. _Context.Ado.IsEnableLogEvent = true;
  1340. this.CurrentConnectionConfig = config;
  1341. _ThreadId = Thread.CurrentThread.ManagedThreadId.ToString();
  1342. if (this.MappingTables == null)
  1343. this.MappingTables = new MappingTableList();
  1344. if (this.MappingColumns == null)
  1345. this.MappingColumns = new MappingColumnList();
  1346. if (this.IgnoreColumns == null)
  1347. this.IgnoreColumns = new IgnoreColumnList();
  1348. if (this.IgnoreInsertColumns == null)
  1349. this.IgnoreInsertColumns = new IgnoreColumnList();
  1350. }
  1351. private void InitConfigs(List<ConnectionConfig> configs)
  1352. {
  1353. foreach (var item in configs)
  1354. {
  1355. if (item.ConfigId == null)
  1356. {
  1357. item.ConfigId = "";
  1358. }
  1359. }
  1360. }
  1361. private void AllClientEach(Action<ISqlSugarClient> action)
  1362. {
  1363. if (this._AllClients == null)
  1364. {
  1365. this._AllClients = new List<SugarTenant>();
  1366. this._AllClients.Add(new SugarTenant() { ConnectionConfig=this.CurrentConnectionConfig, Context=this.Context });
  1367. }
  1368. if (_AllClients.HasValue())
  1369. {
  1370. foreach (var item in _AllClients.Where(it => it.Context.HasValue()))
  1371. {
  1372. action(item.Context);
  1373. }
  1374. }
  1375. }
  1376. private async Task AllClientEachAsync(Func<ISqlSugarClient,Task> action)
  1377. {
  1378. if (this._AllClients == null)
  1379. {
  1380. this._AllClients = new List<SugarTenant>();
  1381. this._AllClients.Add(new SugarTenant() { ConnectionConfig = this.CurrentConnectionConfig, Context = this.Context });
  1382. }
  1383. if (_AllClients.HasValue())
  1384. {
  1385. foreach (var item in _AllClients.Where(it => it.Context.HasValue()))
  1386. {
  1387. await action(item.Context);
  1388. }
  1389. }
  1390. }
  1391. private void InitTenant(SugarTenant Tenant)
  1392. {
  1393. if (Tenant.Context == null)
  1394. {
  1395. Tenant.Context = new SqlSugarProvider(Tenant.ConnectionConfig);
  1396. }
  1397. _Context = Tenant.Context;
  1398. this.CurrentConnectionConfig = Tenant.ConnectionConfig;
  1399. }
  1400. #endregion
  1401. #region Tenant Crud
  1402. public ISugarQueryable<T> QueryableWithAttr<T>()
  1403. {
  1404. var result= this.GetConnectionWithAttr<T>().Queryable<T>();
  1405. result.QueryBuilder.IsCrossQueryWithAttr= true;
  1406. return result;
  1407. }
  1408. public IInsertable<T> InsertableWithAttr<T>(T insertObj) where T : class, new()
  1409. {
  1410. var result= this.GetConnectionWithAttr<T>().Insertable(insertObj);
  1411. result.InsertBuilder.IsWithAttr = true;
  1412. return result;
  1413. }
  1414. public IInsertable<T> InsertableWithAttr<T>(List<T> insertObjs) where T : class, new()
  1415. {
  1416. var result= this.GetConnectionWithAttr<T>().Insertable(insertObjs);
  1417. result.InsertBuilder.IsWithAttr = true;
  1418. return result;
  1419. }
  1420. public IUpdateable<T> UpdateableWithAttr<T>(T updateObj) where T : class, new()
  1421. {
  1422. return this.GetConnectionWithAttr<T>().Updateable(updateObj);
  1423. }
  1424. public IUpdateable<T> UpdateableWithAttr<T>() where T : class, new()
  1425. {
  1426. return this.GetConnectionWithAttr<T>().Updateable<T>();
  1427. }
  1428. public IUpdateable<T> UpdateableWithAttr<T>(List<T> updateObjs) where T : class, new()
  1429. {
  1430. return this.GetConnectionWithAttr<T>().Updateable(updateObjs);
  1431. }
  1432. public IDeleteable<T> DeleteableWithAttr<T>(T deleteObject) where T : class, new()
  1433. {
  1434. return this.GetConnectionWithAttr<T>().Deleteable(deleteObject);
  1435. }
  1436. public IDeleteable<T> DeleteableWithAttr<T>() where T : class, new()
  1437. {
  1438. return this.GetConnectionWithAttr<T>().Deleteable<T>();
  1439. }
  1440. public IDeleteable<T> DeleteableWithAttr<T>(List<T> deleteObjects) where T : class, new()
  1441. {
  1442. return this.GetConnectionWithAttr<T>().Deleteable(deleteObjects);
  1443. }
  1444. #endregion
  1445. }
  1446. }