SqlSugarHelper.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using SqlSugar;
  2. namespace ServiceCenter.SqlSugars
  3. {
  4. /// <summary>
  5. /// ORM
  6. /// </summary>
  7. public class SqlSugarHelper
  8. {
  9. /// <summary>
  10. /// 数据库连接
  11. /// </summary>
  12. private static SqlSugarScope? _Db { get; set; } = null;
  13. /// <summary>
  14. /// 默认数据库连接Key
  15. /// </summary>
  16. private static string _Default { get; set; } = "";
  17. /// <summary>
  18. /// Dlog数据库连接Key
  19. /// </summary>
  20. private static string _Dlog { get; set; } = "";
  21. /// <summary>
  22. /// 设置数据库连接Key
  23. /// </summary>
  24. /// <param name="configId">默认多租户ID</param>
  25. public static void SetDefault(string configId)
  26. {
  27. _Default = configId;
  28. }
  29. /// <summary>
  30. /// 设置 Dlog数据库连接Key
  31. /// </summary>
  32. /// <param name="configId">多租户Dlog ID</param>
  33. public static void SetDlog(string configId)
  34. {
  35. _Dlog = configId;
  36. }
  37. /// <summary>
  38. /// 默认数据库连接Key
  39. /// </summary>
  40. public SqlSugarScopeProvider Default
  41. {
  42. get
  43. {
  44. if (_Default == "") throw new Exception("请调用[SqlSugarHelper.SetDefault]方法设置默认数据库连接");
  45. if (_Db == null) throw new Exception("请调用[SqlSugarHelper.SetDb]方法设置设置数据库连接");
  46. return _Db.GetConnectionScope(_Default);
  47. }
  48. }
  49. /// <summary>
  50. /// Dlog数据库连接Key
  51. /// </summary>
  52. public SqlSugarScopeProvider Dlog
  53. {
  54. get
  55. {
  56. if (_Dlog == "") throw new Exception("请调用[SqlSugarHelper.SetDlog]方法设置默认数据库连接");
  57. if (_Db == null) throw new Exception("请调用[SqlSugarHelper.SetDb]方法设置设置数据库连接");
  58. return _Db.GetConnectionScope(_Dlog);
  59. }
  60. }
  61. /// <summary>
  62. /// 设置数据库连接
  63. /// </summary>
  64. /// <param name="sqlSugarScope"></param>
  65. public static void SetDb(SqlSugarScope sqlSugarScope)
  66. {
  67. _Db = sqlSugarScope;
  68. }
  69. /// <summary>
  70. /// 数据库连接
  71. /// 注意需要
  72. /// </summary>
  73. public SqlSugarScope Connect
  74. {
  75. get
  76. {
  77. return _Db ?? throw new Exception("请调用[SqlSugarHelper.SetDb]方法设置设置数据库连接");
  78. }
  79. }
  80. /// <summary>
  81. /// 执行事务
  82. /// </summary>
  83. /// <param name="act"></param>
  84. /// <exception cref="Exception"></exception>
  85. public static void Do(Action<SqlSugarHelper> act)
  86. {
  87. if (_Db == null) throw new Exception("请调用[SqlSugarHelper.SetDb]方法设置设置数据库连接");
  88. var db = new SqlSugarHelper();
  89. try
  90. {
  91. db.Connect.BeginTran();//开始事务
  92. act(db);//执行委托
  93. db.Connect.CommitTran();//提交事务
  94. }
  95. catch (Exception ex)
  96. {
  97. db.Connect.RollbackTran();//回滚事务
  98. throw new Exception($"事务回滚记录:{ex.Message}:{ex.StackTrace}");
  99. }
  100. }
  101. }
  102. }