SplitTableDeleteProvider.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. namespace SqlSugar
  8. {
  9. public class SplitTableDeleteProvider<T> where T : class, new()
  10. {
  11. public ISqlSugarClient Context;
  12. public DeleteableProvider<T> deleteobj;
  13. public IEnumerable<SplitTableInfo> Tables { get; set; }
  14. public int ExecuteCommand()
  15. {
  16. if (this.Context.Ado.Transaction == null)
  17. {
  18. try
  19. {
  20. this.Context.Ado.BeginTran();
  21. var result = _ExecuteCommand();
  22. this.Context.Ado.CommitTran();
  23. return result;
  24. }
  25. catch (Exception ex)
  26. {
  27. this.Context.Ado.RollbackTran();
  28. throw ex;
  29. }
  30. }
  31. else
  32. {
  33. return _ExecuteCommand();
  34. }
  35. }
  36. public async Task<int> ExecuteCommandAsync()
  37. {
  38. if (this.Context.Ado.Transaction == null)
  39. {
  40. try
  41. {
  42. this.Context.Ado.BeginTran();
  43. var result = await _ExecuteCommandAsync();
  44. this.Context.Ado.CommitTran();
  45. return result;
  46. }
  47. catch (Exception ex)
  48. {
  49. this.Context.Ado.RollbackTran();
  50. throw ex;
  51. }
  52. }
  53. else
  54. {
  55. return await _ExecuteCommandAsync();
  56. }
  57. }
  58. internal int _ExecuteCommand()
  59. {
  60. var result = 0;
  61. var sqlobj = deleteobj.ToSql();
  62. foreach (var item in Tables)
  63. {
  64. var newsqlobj = GetSqlObj(sqlobj, item.TableName);
  65. result +=this.Context.Ado.ExecuteCommand(newsqlobj.Key, newsqlobj.Value);
  66. }
  67. return result;
  68. }
  69. internal async Task<int> _ExecuteCommandAsync()
  70. {
  71. var result = 0;
  72. var sqlobj = deleteobj.ToSql();
  73. foreach (var item in Tables)
  74. {
  75. var newsqlobj = GetSqlObj(sqlobj, item.TableName);
  76. result +=await this.Context.Ado.ExecuteCommandAsync(newsqlobj.Key, newsqlobj.Value);
  77. }
  78. return result;
  79. }
  80. private KeyValuePair<string, List<SugarParameter>> GetSqlObj(KeyValuePair<string, List<SugarParameter>> keyValuePair,string asName)
  81. {
  82. List<SugarParameter> pars = new List<SugarParameter>();
  83. string sql = keyValuePair.Key;
  84. if (keyValuePair.Value != null)
  85. {
  86. pars = keyValuePair.Value.Select(it => new SugarParameter(it.ParameterName, it.Value)).ToList();
  87. }
  88. sql = Regex.Replace(sql, deleteobj.EntityInfo.DbTableName, asName,RegexOptions.IgnoreCase);
  89. return new KeyValuePair<string, List<SugarParameter>>(sql,pars);
  90. }
  91. }
  92. }