DeleteableProvider.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace SqlSugar
  12. {
  13. public class DeleteableProvider<T> : IDeleteable<T> where T : class, new()
  14. {
  15. public ISqlSugarClient Context { get; set; }
  16. public IAdo Db { get { return Context.Ado; } }
  17. public ISqlBuilder SqlBuilder { get; set; }
  18. public DeleteBuilder DeleteBuilder { get; set; }
  19. public MappingTableList OldMappingTableList { get; set; }
  20. public bool IsAs { get; set; }
  21. public bool IsEnableDiffLogEvent { get; set; }
  22. public DiffLogModel diffModel { get; set; }
  23. public List<string> tempPrimaryKeys { get; set; }
  24. internal Action RemoveCacheFunc { get; set; }
  25. internal List<T> DeleteObjects { get; set; }
  26. public EntityInfo EntityInfo
  27. {
  28. get
  29. {
  30. return this.Context.EntityMaintenance.GetEntityInfo<T>();
  31. }
  32. }
  33. public void AddQueue()
  34. {
  35. var sqlObj = this.ToSql();
  36. this.Context.Queues.Add(sqlObj.Key, sqlObj.Value);
  37. }
  38. public int ExecuteCommand()
  39. {
  40. string sql;
  41. SugarParameter[] paramters;
  42. _ExecuteCommand(out sql, out paramters);
  43. var result = Db.ExecuteCommand(sql, paramters);
  44. After(sql);
  45. return result;
  46. }
  47. public bool ExecuteCommandHasChange()
  48. {
  49. return ExecuteCommand() > 0;
  50. }
  51. public Task<int> ExecuteCommandAsync(CancellationToken token)
  52. {
  53. this.Context.Ado.CancellationToken= token;
  54. return ExecuteCommandAsync();
  55. }
  56. public async Task<int> ExecuteCommandAsync()
  57. {
  58. string sql;
  59. SugarParameter[] paramters;
  60. _ExecuteCommand(out sql, out paramters);
  61. var result = await Db.ExecuteCommandAsync(sql, paramters);
  62. After(sql);
  63. return result;
  64. }
  65. public async Task<bool> ExecuteCommandHasChangeAsync()
  66. {
  67. return await ExecuteCommandAsync() > 0;
  68. }
  69. public IDeleteable<T> AsType(Type tableNameType)
  70. {
  71. return AS(this.Context.EntityMaintenance.GetEntityInfo(tableNameType).DbTableName);
  72. }
  73. public IDeleteable<T> AS(string tableName)
  74. {
  75. if (tableName == null) return this;
  76. //var entityName = typeof(T).Name;
  77. //IsAs = true;
  78. //OldMappingTableList = this.Context.MappingTables;
  79. //this.Context.MappingTables = this.Context.Utilities.TranslateCopy(this.Context.MappingTables);
  80. //if (this.Context.MappingTables.Any(it => it.EntityName == entityName))
  81. //{
  82. // this.Context.MappingTables.Add(this.Context.MappingTables.First(it => it.EntityName == entityName).DbTableName, tableName);
  83. //}
  84. //this.Context.MappingTables.Add(entityName, tableName);
  85. this.DeleteBuilder.AsName = tableName;
  86. return this; ;
  87. }
  88. public IDeleteable<T> EnableDiffLogEventIF(bool isEnableDiffLogEvent, object businessData = null)
  89. {
  90. if (isEnableDiffLogEvent)
  91. {
  92. return EnableDiffLogEvent(businessData);
  93. }
  94. else
  95. {
  96. return this;
  97. }
  98. }
  99. public IDeleteable<T> EnableDiffLogEvent(object businessData = null)
  100. {
  101. diffModel = new DiffLogModel();
  102. this.IsEnableDiffLogEvent = true;
  103. diffModel.BusinessData = businessData;
  104. diffModel.DiffType = DiffType.delete;
  105. return this;
  106. }
  107. public IDeleteable<T> Where(List<T> deleteObjs)
  108. {
  109. this.DeleteObjects = deleteObjs;
  110. if (deleteObjs == null || deleteObjs.Count() == 0)
  111. {
  112. Where(SqlBuilder.SqlFalse);
  113. return this;
  114. }
  115. DataAop(deleteObjs);
  116. string tableName = this.Context.EntityMaintenance.GetTableName<T>();
  117. var primaryFields = this.GetPrimaryKeys();
  118. var isSinglePrimaryKey = primaryFields.Count == 1;
  119. Check.Exception(primaryFields.IsNullOrEmpty(), string.Format("Table {0} with no primarykey", tableName));
  120. if (isSinglePrimaryKey)
  121. {
  122. List<object> primaryKeyValues = new List<object>();
  123. var primaryField = primaryFields.Single();
  124. foreach (var deleteObj in deleteObjs)
  125. {
  126. var entityPropertyName = this.Context.EntityMaintenance.GetPropertyName<T>(primaryField);
  127. var columnInfo = EntityInfo.Columns.Single(it => it.PropertyName.Equals(entityPropertyName, StringComparison.CurrentCultureIgnoreCase));
  128. var value = columnInfo.PropertyInfo.GetValue(deleteObj, null);
  129. value = UtilMethods.GetConvertValue(value);
  130. if (this.Context.CurrentConnectionConfig?.MoreSettings?.TableEnumIsString!=true&&
  131. columnInfo.SqlParameterDbType==null&&
  132. columnInfo.PropertyInfo.PropertyType.IsEnum())
  133. {
  134. value = Convert.ToInt64(value);
  135. }
  136. primaryKeyValues.Add(value);
  137. }
  138. if (primaryKeyValues.Count < 10000)
  139. {
  140. var inValueString = primaryKeyValues.ToArray().ToJoinSqlInVals();
  141. Where(string.Format(DeleteBuilder.WhereInTemplate, SqlBuilder.GetTranslationColumnName(primaryFields.Single()), inValueString));
  142. }
  143. else
  144. {
  145. if (DeleteBuilder.BigDataInValues == null)
  146. DeleteBuilder.BigDataInValues = new List<object>();
  147. DeleteBuilder.BigDataInValues.AddRange(primaryKeyValues);
  148. DeleteBuilder.BigDataFiled = primaryField;
  149. }
  150. }
  151. else
  152. {
  153. StringBuilder whereInSql = new StringBuilder();
  154. foreach (var deleteObj in deleteObjs)
  155. {
  156. StringBuilder orString = new StringBuilder();
  157. var isFirst = deleteObjs.IndexOf(deleteObj) == 0;
  158. if (!isFirst)
  159. {
  160. orString.Append(DeleteBuilder.WhereInOrTemplate + UtilConstants.Space);
  161. }
  162. int i = 0;
  163. StringBuilder andString = new StringBuilder();
  164. foreach (var primaryField in primaryFields)
  165. {
  166. if (i != 0)
  167. andString.Append(DeleteBuilder.WhereInAndTemplate + UtilConstants.Space);
  168. //var entityPropertyName = this.EntityInfo.Columns.Single(it=>it.PropertyName.EqualCase(primaryField)||it.DbColumnName.EqualCase(primaryField)).PropertyName;
  169. var columnInfo = EntityInfo.Columns.Single(t => t.PropertyName.EqualCase(primaryField) || t.DbColumnName.EqualCase(primaryField));
  170. var entityValue = columnInfo.PropertyInfo.GetValue(deleteObj, null);
  171. if (this.Context.CurrentConnectionConfig?.MoreSettings?.TableEnumIsString != true &&
  172. columnInfo.SqlParameterDbType == null &&
  173. columnInfo.PropertyInfo.PropertyType.IsEnum())
  174. {
  175. entityValue = Convert.ToInt64(entityValue);
  176. }
  177. var tempequals = DeleteBuilder.WhereInEqualTemplate;
  178. if (this.Context.CurrentConnectionConfig.MoreSettings != null && this.Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar == true)
  179. {
  180. tempequals = $"{SqlBuilder.SqlTranslationLeft}{{0}}{SqlBuilder.SqlTranslationRight}='{{1}}' ";
  181. }
  182. if (SqlBuilder.SqlParameterKeyWord==":")
  183. {
  184. var isAutoToUpper =this.Context.CurrentConnectionConfig?.MoreSettings?.IsAutoToUpper??true;
  185. if (entityValue != null && UtilMethods.GetUnderType(entityValue.GetType()) == UtilConstants.DateType)
  186. {
  187. andString.AppendFormat("\"{0}\"={1} ", primaryField.ToUpper(isAutoToUpper), "to_date('" + entityValue.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss") + "', 'YYYY-MM-DD HH24:MI:SS') ");
  188. }
  189. else
  190. {
  191. andString.AppendFormat(tempequals.Replace("N","")+" ", primaryField.ToUpper(isAutoToUpper), entityValue);
  192. }
  193. }
  194. else if (this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL && (this.Context.CurrentConnectionConfig.MoreSettings == null || this.Context.CurrentConnectionConfig.MoreSettings?.PgSqlIsAutoToLower == true))
  195. {
  196. andString.AppendFormat("\"{0}\"={1} ", primaryField.ToLower(), new PostgreSQLExpressionContext().GetValue(entityValue));
  197. }
  198. else if ( entityValue != null &&UtilMethods.IsNumber( UtilMethods.GetUnderType(entityValue.GetType()).Name))
  199. {
  200. andString.AppendFormat("{0}={1} ", this.SqlBuilder.GetTranslationColumnName(primaryField), $"{entityValue}");
  201. }
  202. else if (entityValue != null && UtilMethods.GetUnderType(entityValue.GetType()) == UtilConstants.DateType)
  203. {
  204. andString.AppendFormat("{0}={1} ", this.SqlBuilder.GetTranslationColumnName(primaryField), this.DeleteBuilder.LambdaExpressions.DbMehtods.ToDate(new MethodCallExpressionModel()
  205. {
  206. Args = new List<MethodCallExpressionArgs>()
  207. {
  208. new MethodCallExpressionArgs()
  209. {
  210. IsMember=false,
  211. MemberName="'"+entityValue.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.fff")+"'"
  212. }
  213. }
  214. })); ;
  215. }
  216. else
  217. {
  218. if ((columnInfo.SqlParameterDbType.ObjToString() == System.Data.DbType.AnsiString.ObjToString()) || !(entityValue is string) || this.Context.CurrentConnectionConfig?.MoreSettings?.DisableNvarchar == true)
  219. {
  220. tempequals = tempequals.Replace("=N'", "='");
  221. }
  222. else
  223. {
  224. tempequals = SqlBuilder.RemoveN(tempequals);
  225. }
  226. entityValue = UtilMethods.GetConvertValue(entityValue);
  227. andString.AppendFormat(tempequals, primaryField, entityValue);
  228. }
  229. ++i;
  230. }
  231. orString.AppendFormat(DeleteBuilder.WhereInAreaTemplate, andString);
  232. whereInSql.Append(orString);
  233. }
  234. Where(string.Format(DeleteBuilder.WhereInAreaTemplate, whereInSql.ToString()));
  235. }
  236. return this;
  237. }
  238. public IDeleteable<T> WhereIF(bool isWhere, Expression<Func<T, bool>> expression)
  239. {
  240. Check.ExceptionEasy(!StaticConfig.EnableAllWhereIF, "Need to program startup configuration StaticConfig. EnableAllWhereIF = true; Tip: This operation is very risky if there are no conditions it is easy to update the entire table", " 需要程序启动时配置StaticConfig.EnableAllWhereIF=true; 提示:该操作存在很大的风险如果没有条件很容易将整个表全部更新");
  241. if (isWhere)
  242. {
  243. return Where(expression);
  244. }
  245. return this;
  246. }
  247. public IDeleteable<T> Where(Expression<Func<T, bool>> expression)
  248. {
  249. var expResult = DeleteBuilder.GetExpressionValue(expression, ResolveExpressType.WhereSingle);
  250. var whereString = expResult.GetResultString();
  251. if (expression.ToString().Contains("Subqueryable()")) {
  252. var entityTableName = this.EntityInfo.DbTableName;
  253. if (this.DeleteBuilder.AsName.HasValue())
  254. {
  255. entityTableName = this.DeleteBuilder.AsName;
  256. }
  257. if (ExpressionTool.GetParameters(expression).First().Type == typeof(T))
  258. {
  259. var tableName = this.SqlBuilder.GetTranslationColumnName(entityTableName);
  260. whereString = whereString.Replace(tableName, $"( SELECT * FROM {tableName}) ");
  261. }
  262. whereString = whereString.Replace(this.SqlBuilder.GetTranslationColumnName(expression.Parameters.First().Name) + ".", this.SqlBuilder.GetTranslationTableName(entityTableName) + ".");
  263. }
  264. else if (expResult.IsNavicate)
  265. {
  266. var entityTableName2 = this.EntityInfo.DbTableName;
  267. if (this.DeleteBuilder.AsName.HasValue())
  268. {
  269. entityTableName2 = this.DeleteBuilder.AsName;
  270. }
  271. whereString = whereString.Replace(expression.Parameters.First().Name + ".", this.SqlBuilder.GetTranslationTableName(entityTableName2) + ".");
  272. whereString = whereString.Replace(this.SqlBuilder.GetTranslationColumnName(expression.Parameters.First().Name) + ".", this.SqlBuilder.GetTranslationTableName(entityTableName2) + ".");
  273. }
  274. DeleteBuilder.WhereInfos.Add(whereString);
  275. return this;
  276. }
  277. public IDeleteable<T> Where(T deleteObj)
  278. {
  279. Check.Exception(GetPrimaryKeys().IsNullOrEmpty(), "Where(entity) Primary key required");
  280. Where(new List<T>() { deleteObj });
  281. return this;
  282. }
  283. public IDeleteable<T> Where(string whereString, object parameters = null)
  284. {
  285. DeleteBuilder.WhereInfos.Add(whereString);
  286. if (parameters != null)
  287. {
  288. if (DeleteBuilder.Parameters == null)
  289. {
  290. DeleteBuilder.Parameters = new List<SugarParameter>();
  291. }
  292. DeleteBuilder.Parameters.AddRange(Context.Ado.GetParameters(parameters));
  293. }
  294. return this;
  295. }
  296. public IDeleteable<T> Where(string whereString, SugarParameter parameter)
  297. {
  298. DeleteBuilder.WhereInfos.Add(whereString);
  299. if (DeleteBuilder.Parameters == null)
  300. {
  301. DeleteBuilder.Parameters = new List<SugarParameter>();
  302. }
  303. DeleteBuilder.Parameters.Add(parameter);
  304. return this;
  305. }
  306. public IDeleteable<T> Where(string whereString, SugarParameter[] parameters)
  307. {
  308. DeleteBuilder.WhereInfos.Add(whereString);
  309. if (DeleteBuilder.Parameters == null)
  310. {
  311. DeleteBuilder.Parameters = new List<SugarParameter>();
  312. }
  313. DeleteBuilder.Parameters.AddRange(parameters);
  314. return this;
  315. }
  316. public IDeleteable<T> Where(string whereString, List<SugarParameter> parameters)
  317. {
  318. DeleteBuilder.WhereInfos.Add(whereString);
  319. if (DeleteBuilder.Parameters == null)
  320. {
  321. DeleteBuilder.Parameters = new List<SugarParameter>();
  322. }
  323. DeleteBuilder.Parameters.AddRange(parameters);
  324. return this;
  325. }
  326. public IDeleteable<T> Where(List<IConditionalModel> conditionalModels)
  327. {
  328. if (conditionalModels.Count == 0)
  329. {
  330. return Where("1=2");
  331. }
  332. var sql = this.Context.Queryable<T>().SqlBuilder.ConditionalModelToSql(conditionalModels);
  333. var result = this;
  334. result.Where(sql.Key, sql.Value);
  335. return result;
  336. }
  337. public IDeleteable<T> WhereColumns(T data, Expression<Func<T, object>> columns)
  338. {
  339. return WhereColumns(new List<T>() { data },columns);
  340. }
  341. public IDeleteable<T> WhereColumns(List<T> list,Expression<Func<T, object>> columns)
  342. {
  343. if (columns!=null)
  344. {
  345. tempPrimaryKeys = DeleteBuilder.GetExpressionValue(columns, ResolveExpressType.ArraySingle).GetResultArray().Select(it => this.SqlBuilder.GetNoTranslationColumnName(it)).ToList();
  346. }
  347. //else if (columns != null && tempPrimaryKeys.IsNullOrEmpty())
  348. //{
  349. // tempPrimaryKeys = DeleteBuilder.GetExpressionValue(columns, ResolveExpressType.ArraySingle).GetResultArray().Select(it => this.SqlBuilder.GetNoTranslationColumnName(it)).ToList();
  350. //}
  351. this.Where(list);
  352. return this;
  353. }
  354. public IDeleteable<T> WhereColumns(List<Dictionary<string, object>> list)
  355. {
  356. List<IConditionalModel> conditionalModels = new List<IConditionalModel>();
  357. foreach (var model in list)
  358. {
  359. int i = 0;
  360. var clist = new List<KeyValuePair<WhereType, ConditionalModel>>();
  361. foreach (var item in model.Keys)
  362. {
  363. clist.Add(new KeyValuePair<WhereType, ConditionalModel>(i == 0 ? WhereType.Or : WhereType.And, new ConditionalModel()
  364. {
  365. FieldName =item,
  366. ConditionalType = ConditionalType.Equal,
  367. FieldValue = model[item].ObjToString(),
  368. CSharpTypeName = model[item]==null?null : model[item].GetType().Name
  369. }));
  370. i++;
  371. }
  372. conditionalModels.Add(new ConditionalCollections()
  373. {
  374. ConditionalList = clist
  375. });
  376. }
  377. return this.Where(conditionalModels);
  378. }
  379. public IDeleteable<T> RemoveDataCache()
  380. {
  381. this.RemoveCacheFunc = () =>
  382. {
  383. var cacheService = this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService;
  384. CacheSchemeMain.RemoveCache(cacheService, this.Context.EntityMaintenance.GetTableName<T>());
  385. };
  386. return this;
  387. }
  388. public IDeleteable<T> EnableQueryFilter()
  389. {
  390. var queryable = this.Context.Queryable<T>();
  391. queryable.QueryBuilder.LambdaExpressions.ParameterIndex= 1000;
  392. var sqlable= queryable.ToSql();
  393. var whereInfos = Regex.Split(sqlable.Key, " Where ", RegexOptions.IgnoreCase);
  394. if (whereInfos.Length > 1)
  395. {
  396. this.Where(whereInfos.Last(), sqlable.Value);
  397. }
  398. return this;
  399. }
  400. public IDeleteable<T> EnableQueryFilter(Type type)
  401. {
  402. var queryable = this.Context.Queryable<T>().Filter(type);
  403. queryable.QueryBuilder.LambdaExpressions.ParameterIndex = 1000;
  404. var sqlable = queryable.ToSql();
  405. var whereInfos = Regex.Split(sqlable.Key, " Where ", RegexOptions.IgnoreCase);
  406. if (whereInfos.Length > 1)
  407. {
  408. this.Where(whereInfos.Last(), sqlable.Value);
  409. }
  410. return this;
  411. }
  412. public SplitTableDeleteProvider<T> SplitTable(Func<List<SplitTableInfo>, IEnumerable<SplitTableInfo>> getTableNamesFunc)
  413. {
  414. UtilMethods.StartCustomSplitTable(this.Context, typeof(T));
  415. this.Context.MappingTables.Add(this.EntityInfo.EntityName, this.EntityInfo.DbTableName);
  416. SplitTableDeleteProvider<T> result = new SplitTableDeleteProvider<T>();
  417. result.Context = this.Context;
  418. SplitTableContext helper = new SplitTableContext((SqlSugarProvider)Context)
  419. {
  420. EntityInfo = this.EntityInfo
  421. };
  422. var tables = getTableNamesFunc(helper.GetTables());
  423. result.Tables = tables;
  424. result.deleteobj = this;
  425. return result;
  426. }
  427. public SplitTableDeleteByObjectProvider<T> SplitTable()
  428. {
  429. UtilMethods.StartCustomSplitTable(this.Context, typeof(T));
  430. SplitTableDeleteByObjectProvider<T> result = new SplitTableDeleteByObjectProvider<T>();
  431. result.Context = this.Context;
  432. Check.ExceptionEasy(this.DeleteObjects == null, "SplitTable() +0 only List<T> can be deleted", "SplitTable()无参数重载只支持根据实体集合删除");
  433. result.deleteObjects = this.DeleteObjects.ToArray();
  434. SplitTableContext helper = new SplitTableContext((SqlSugarProvider)Context)
  435. {
  436. EntityInfo = this.EntityInfo
  437. };
  438. result.deleteobj = this;
  439. return result;
  440. }
  441. public LogicDeleteProvider<T> IsLogic()
  442. {
  443. LogicDeleteProvider<T> result = new LogicDeleteProvider<T>();
  444. result.DeleteBuilder = this.DeleteBuilder;
  445. result.Deleteable = this;
  446. return result;
  447. }
  448. public IDeleteable<T> RemoveDataCache(string likeString)
  449. {
  450. this.RemoveCacheFunc = () =>
  451. {
  452. var cacheService = this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService;
  453. CacheSchemeMain.RemoveCacheByLike(cacheService, likeString);
  454. };
  455. return this;
  456. }
  457. public IDeleteable<T> In<PkType>(List<PkType> primaryKeyValues)
  458. {
  459. if (primaryKeyValues == null || primaryKeyValues.Count() == 0)
  460. {
  461. Where(SqlBuilder.SqlFalse);
  462. return this;
  463. }
  464. return In<PkType>(primaryKeyValues.ToArray());
  465. }
  466. public IDeleteable<T> In<PkType>(PkType[] primaryKeyValues)
  467. {
  468. if (primaryKeyValues == null || primaryKeyValues.Count() == 0)
  469. {
  470. Where(SqlBuilder.SqlFalse);
  471. return this;
  472. }
  473. string tableName = this.Context.EntityMaintenance.GetTableName<T>();
  474. string primaryField = null;
  475. primaryField = GetPrimaryKeys().FirstOrDefault();
  476. Check.ArgumentNullException(primaryField, "Table " + tableName + " with no primarykey");
  477. if (primaryKeyValues.Length < 10000)
  478. {
  479. Where(string.Format(DeleteBuilder.WhereInTemplate, SqlBuilder.GetTranslationColumnName(primaryField), primaryKeyValues.ToJoinSqlInVals()));
  480. }
  481. else
  482. {
  483. if (DeleteBuilder.BigDataInValues == null)
  484. DeleteBuilder.BigDataInValues = new List<object>();
  485. DeleteBuilder.BigDataInValues.AddRange(primaryKeyValues.Select(it => (object)it));
  486. DeleteBuilder.BigDataFiled = primaryField;
  487. }
  488. return this;
  489. }
  490. public IDeleteable<T> In<PkType>(PkType primaryKeyValue)
  491. {
  492. if (typeof(PkType).FullName.IsCollectionsList())
  493. {
  494. var newValues = new List<object>();
  495. foreach (var item in primaryKeyValue as IEnumerable)
  496. {
  497. newValues.Add(item);
  498. }
  499. return In(newValues);
  500. }
  501. In(new PkType[] { primaryKeyValue });
  502. return this;
  503. }
  504. public IDeleteable<T> In<PkType>(Expression<Func<T, object>> inField, PkType primaryKeyValue)
  505. {
  506. var lamResult = DeleteBuilder.GetExpressionValue(inField, ResolveExpressType.FieldSingle);
  507. var fieldName = lamResult.GetResultString();
  508. tempPrimaryKeys = new List<string>() { fieldName };
  509. var result = In(primaryKeyValue);
  510. tempPrimaryKeys = null;
  511. return this;
  512. }
  513. public IDeleteable<T> In<PkType>(Expression<Func<T, object>> inField, PkType[] primaryKeyValues)
  514. {
  515. var lamResult = DeleteBuilder.GetExpressionValue(inField, ResolveExpressType.FieldSingle);
  516. var fieldName = lamResult.GetResultString();
  517. tempPrimaryKeys = new List<string>() { fieldName };
  518. var result = In(primaryKeyValues);
  519. tempPrimaryKeys = null;
  520. return this;
  521. }
  522. public IDeleteable<T> In<PkType>(Expression<Func<T, object>> inField, List<PkType> primaryKeyValues)
  523. {
  524. var lamResult = DeleteBuilder.GetExpressionValue(inField, ResolveExpressType.FieldSingle);
  525. var fieldName = lamResult.GetResultString();
  526. tempPrimaryKeys = new List<string>() { fieldName };
  527. var result = In(primaryKeyValues);
  528. tempPrimaryKeys = null;
  529. return this;
  530. }
  531. public IDeleteable<T> In<PkType>(Expression<Func<T, object>> inField, ISugarQueryable<PkType> childQueryExpression)
  532. {
  533. var lamResult = DeleteBuilder.GetExpressionValue(inField, ResolveExpressType.FieldSingle);
  534. var fieldName = lamResult.GetResultString();
  535. var sql= childQueryExpression.ToSql();
  536. Where($" {fieldName} IN ( SELECT {fieldName} FROM ( {sql.Key} ) SUBDEL) ",sql.Value);
  537. return this;
  538. }
  539. public IDeleteable<T> In<PkType>(string inField, List<PkType> primaryKeyValues)
  540. {
  541. tempPrimaryKeys = new List<string>() { inField };
  542. var result = In(primaryKeyValues);
  543. tempPrimaryKeys = null;
  544. return this;
  545. }
  546. public DeleteablePage<T> PageSize(int pageSize)
  547. {
  548. Check.ExceptionEasy(this.DeleteObjects == null, "PageSize can only be deleted as a List<Class> entity collection", "Deleteable.PageSize()只能是List<Class>实体集合方式删除,并且集合不能为null");
  549. DeleteablePage<T> result = new DeleteablePage<T>();
  550. result.DataList = this.DeleteObjects.ToArray();
  551. result.Context = this.Context;
  552. result.DiffModel = this.diffModel;
  553. result.IsEnableDiffLogEvent= this.IsEnableDiffLogEvent;
  554. result.TableName = this.DeleteBuilder.AsName;
  555. result.PageSize = pageSize;
  556. return result;
  557. }
  558. public IDeleteable<T> With(string lockString)
  559. {
  560. if (this.Context.CurrentConnectionConfig.DbType == DbType.SqlServer)
  561. DeleteBuilder.TableWithString = lockString;
  562. return this;
  563. }
  564. public virtual string ToSqlString()
  565. {
  566. var sqlObj = this.ToSql();
  567. var result = sqlObj.Key;
  568. if (result == null) return null;
  569. result = UtilMethods.GetSqlString(this.Context.CurrentConnectionConfig, sqlObj);
  570. return result;
  571. }
  572. public KeyValuePair<string, List<SugarParameter>> ToSql()
  573. {
  574. DeleteBuilder.EntityInfo = this.Context.EntityMaintenance.GetEntityInfo<T>();
  575. string sql = DeleteBuilder.ToSqlString();
  576. var paramters = DeleteBuilder.Parameters == null ? null : DeleteBuilder.Parameters.ToList();
  577. RestoreMapping();
  578. return new KeyValuePair<string, List<SugarParameter>>(sql, paramters);
  579. }
  580. private List<string> GetPrimaryKeys()
  581. {
  582. if (tempPrimaryKeys.HasValue())
  583. {
  584. return tempPrimaryKeys;
  585. }
  586. else if (this.Context.IsSystemTablesConfig)
  587. {
  588. return this.Context.DbMaintenance.GetPrimaries(this.Context.EntityMaintenance.GetTableName(this.EntityInfo.EntityName));
  589. }
  590. else
  591. {
  592. return this.EntityInfo.Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToList();
  593. }
  594. }
  595. private void _ExecuteCommand(out string sql, out SugarParameter[] paramters)
  596. {
  597. DeleteBuilder.EntityInfo = this.Context.EntityMaintenance.GetEntityInfo<T>();
  598. sql = DeleteBuilder.ToSqlString();
  599. paramters = DeleteBuilder.Parameters == null ? null : DeleteBuilder.Parameters.ToArray();
  600. RestoreMapping();
  601. AutoRemoveDataCache();
  602. Before(sql);
  603. }
  604. protected virtual List<string> GetIdentityKeys()
  605. {
  606. if (this.Context.IsSystemTablesConfig)
  607. {
  608. return this.Context.DbMaintenance.GetIsIdentities(this.Context.EntityMaintenance.GetTableName(this.EntityInfo.EntityName));
  609. }
  610. else
  611. {
  612. return this.EntityInfo.Columns.Where(it => it.IsIdentity).Select(it => it.DbColumnName).ToList();
  613. }
  614. }
  615. private void RestoreMapping()
  616. {
  617. if (IsAs)
  618. {
  619. this.Context.MappingTables = OldMappingTableList;
  620. }
  621. }
  622. //private void TaskStart<Type>(Task<Type> result)
  623. //{
  624. // if (this.Context.CurrentConnectionConfig.IsShardSameThread)
  625. // {
  626. // Check.Exception(true, "IsShardSameThread=true can't be used async method");
  627. // }
  628. // result.Start();
  629. //}
  630. private void AutoRemoveDataCache()
  631. {
  632. var moreSetts = this.Context.CurrentConnectionConfig.MoreSettings;
  633. var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices;
  634. if (moreSetts != null && moreSetts.IsAutoRemoveDataCache && extService != null && extService.DataInfoCacheService != null)
  635. {
  636. this.RemoveDataCache();
  637. }
  638. }
  639. private void After(string sql)
  640. {
  641. if (this.IsEnableDiffLogEvent)
  642. {
  643. var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation;
  644. this.Context.Ado.IsDisableMasterSlaveSeparation = true;
  645. var parameters = DeleteBuilder.Parameters;
  646. if (parameters == null)
  647. parameters = new List<SugarParameter>();
  648. diffModel.AfterData = null;
  649. diffModel.Time = this.Context.Ado.SqlExecutionTime;
  650. if (this.Context.CurrentConnectionConfig.AopEvents.OnDiffLogEvent != null)
  651. this.Context.CurrentConnectionConfig.AopEvents.OnDiffLogEvent(diffModel);
  652. this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation;
  653. }
  654. if (this.RemoveCacheFunc != null) {
  655. this.RemoveCacheFunc();
  656. }
  657. }
  658. private void Before(string sql)
  659. {
  660. if (this.IsEnableDiffLogEvent)
  661. {
  662. var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation;
  663. this.Context.Ado.IsDisableMasterSlaveSeparation = true;
  664. var parameters = DeleteBuilder.Parameters;
  665. if (parameters == null)
  666. parameters = new List<SugarParameter>();
  667. diffModel.BeforeData = GetDiffTable(sql, parameters);
  668. diffModel.Sql = sql;
  669. diffModel.Parameters = parameters.ToArray();
  670. this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation;
  671. }
  672. }
  673. private List<DiffLogTableInfo> GetDiffTable(string sql, List<SugarParameter> parameters)
  674. {
  675. List<DiffLogTableInfo> result = new List<DiffLogTableInfo>();
  676. var whereSql = Regex.Replace(sql, ".* WHERE ", "", RegexOptions.Singleline);
  677. var dt = this.Context.Queryable<T>().AS(this.DeleteBuilder.AsName).Filter(null, true).Where(whereSql).AddParameters(parameters).ToDataTable();
  678. if (dt.Rows != null && dt.Rows.Count > 0)
  679. {
  680. foreach (DataRow row in dt.Rows)
  681. {
  682. DiffLogTableInfo item = new DiffLogTableInfo();
  683. item.TableDescription = this.EntityInfo.TableDescription;
  684. item.TableName = this.EntityInfo.DbTableName;
  685. item.Columns = new List<DiffLogColumnInfo>();
  686. foreach (DataColumn col in dt.Columns)
  687. {
  688. var sugarColumn = this.EntityInfo.Columns.Where(it => it.DbColumnName != null).First(it =>
  689. it.DbColumnName.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase));
  690. DiffLogColumnInfo addItem = new DiffLogColumnInfo();
  691. addItem.Value = row[col.ColumnName];
  692. addItem.ColumnName = col.ColumnName;
  693. addItem.IsPrimaryKey = sugarColumn.IsPrimarykey;
  694. addItem.ColumnDescription = sugarColumn.ColumnDescription;
  695. item.Columns.Add(addItem);
  696. }
  697. result.Add(item);
  698. }
  699. }
  700. return result;
  701. }
  702. private void DataAop(object deleteObj)
  703. {
  704. var dataEvent = this.Context.CurrentConnectionConfig.AopEvents?.DataExecuting;
  705. if (deleteObj != null&& dataEvent!=null)
  706. {
  707. var model = new DataFilterModel()
  708. {
  709. OperationType = DataFilterType.DeleteByObject,
  710. EntityValue = deleteObj,
  711. EntityColumnInfo=this.EntityInfo.Columns.FirstOrDefault()
  712. };
  713. dataEvent(deleteObj,model);
  714. }
  715. }
  716. }
  717. }