平安校园
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

215 satır
8.0 KiB

  1. //
  2. using DbType = SqlSugar.DbType;
  3. namespace SafeCampus.SqlSugar;
  4. /// <summary>
  5. /// 数据库上下文对象
  6. /// </summary>
  7. public static class DbContext
  8. {
  9. /// <summary>
  10. /// 读取配置文件中的 ConnectionStrings:SqlSugar 配置节点
  11. /// </summary>
  12. public static readonly List<SqlSugarConfig> DB_CONFIGS = App.GetConfig<List<SqlSugarConfig>>("SqlSugarSettings:ConnectionStrings");
  13. /// <summary>
  14. /// SqlSugar 数据库实例
  15. /// </summary>
  16. public static readonly SqlSugarScope DB = new SqlSugarScope(DB_CONFIGS.Adapt<List<ConnectionConfig>>(), db =>
  17. {
  18. //遍历配置的数据库
  19. DB_CONFIGS.ForEach(it =>
  20. {
  21. var sqlSugarScope = db.GetConnectionScope(it.ConfigId);//获取当前库
  22. MoreSetting(sqlSugarScope, it.DbType);//更多设置
  23. ExternalServicesSetting(sqlSugarScope, it);//实体拓展配置
  24. AopSetting(sqlSugarScope);//aop配置
  25. FilterSetting(sqlSugarScope);//过滤器配置
  26. });
  27. });
  28. /// <summary>
  29. /// 实体拓展配置,自定义类型多库兼容
  30. /// </summary>
  31. /// <param name="db"></param>
  32. /// <param name="config"></param>
  33. private static void ExternalServicesSetting(SqlSugarScopeProvider db, SqlSugarConfig config)
  34. {
  35. db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices
  36. {
  37. // 处理表
  38. EntityNameService = (type, entity) =>
  39. {
  40. if (config.IsUnderLine && !entity.DbTableName.Contains('_'))
  41. entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName);// 驼峰转下划线
  42. },
  43. //自定义类型多库兼容
  44. EntityService = (c, p) =>
  45. {
  46. //如果是mysql并且是varchar(max) 已弃用
  47. //if (config.DbType == SqlSugar.DbType.MySql && (p.DataType == SqlSugarConst.NVarCharMax))
  48. //{
  49. // p.DataType = SqlSugarConst.LongText;//转成mysql的longtext
  50. //}
  51. //else if (config.DbType == SqlSugar.DbType.Sqlite && (p.DataType == SqlSugarConst.NVarCharMax))
  52. //{
  53. // p.DataType = SqlSugarConst.Text;//转成sqlite的text
  54. //}
  55. //默认不写IsNullable为非必填
  56. //if (new NullabilityInfoContext().Create(c).WriteState is NullabilityState.Nullable)
  57. // p.IsNullable = true;
  58. if (config.IsUnderLine && !p.IsIgnore && !p.DbColumnName.Contains('_'))
  59. p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);// 驼峰转下划线
  60. }
  61. };
  62. }
  63. /// <summary>
  64. /// Aop设置
  65. /// </summary>
  66. /// <param name="db"></param>
  67. public static void AopSetting(SqlSugarScopeProvider db)
  68. {
  69. var config = db.CurrentConnectionConfig;
  70. // 设置超时时间
  71. db.Ado.CommandTimeOut = 30;
  72. // 打印SQL语句
  73. db.Aop.OnLogExecuting = (sql, pars) =>
  74. {
  75. //如果不是开发环境就打印sql
  76. if (App.HostEnvironment.IsDevelopment())
  77. {
  78. if (sql.StartsWith("SELECT"))
  79. {
  80. Console.ForegroundColor = ConsoleColor.Green;
  81. WriteSqlLog($"查询{config.ConfigId}库操作");
  82. }
  83. if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
  84. {
  85. Console.ForegroundColor = ConsoleColor.Blue;
  86. WriteSqlLog($"修改{config.ConfigId}库操作");
  87. }
  88. if (sql.StartsWith("DELETE"))
  89. {
  90. Console.ForegroundColor = ConsoleColor.Red;
  91. WriteSqlLog($"删除{config.ConfigId}库操作");
  92. }
  93. Console.WriteLine(UtilMethods.GetSqlString(config.DbType, sql, pars));
  94. WriteSqlLog($"{config.ConfigId}库操作结束");
  95. Console.ForegroundColor = ConsoleColor.White;
  96. Console.WriteLine();
  97. }
  98. };
  99. //异常
  100. db.Aop.OnError = ex =>
  101. {
  102. //如果不是开发环境就打印日志
  103. if (App.WebHostEnvironment.IsDevelopment())
  104. {
  105. if (ex.Parametres == null) return;
  106. Console.ForegroundColor = ConsoleColor.Red;
  107. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  108. WriteSqlLog($"{config.ConfigId}库操作异常");
  109. Console.WriteLine(UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  110. Console.ForegroundColor = ConsoleColor.White;
  111. }
  112. };
  113. //插入和更新过滤器
  114. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  115. {
  116. // 新增操作
  117. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  118. {
  119. // 主键(long类型)且没有值的---赋值雪花Id
  120. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  121. {
  122. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  123. if (id == null || (long)id == 0)
  124. entityInfo.SetValue(CommonUtils.GetSingleId());
  125. }
  126. if (entityInfo.PropertyName == nameof(BaseEntity.CreateTime))
  127. entityInfo.SetValue(DateTime.Now);
  128. if (App.User != null)
  129. {
  130. //创建人和创建机构ID
  131. if (entityInfo.PropertyName == nameof(BaseEntity.CreateUserId))
  132. entityInfo.SetValue(App.User.FindFirst(ClaimConst.USER_ID)?.Value);
  133. if (entityInfo.PropertyName == nameof(BaseEntity.CreateUser))
  134. entityInfo.SetValue(App.User.FindFirst(ClaimConst.ACCOUNT)?.Value);
  135. if (entityInfo.PropertyName == nameof(DataEntityBase.CreateOrgId))
  136. entityInfo.SetValue(App.User.FindFirst(ClaimConst.ORG_ID)?.Value);
  137. }
  138. }
  139. // 更新操作
  140. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  141. {
  142. //更新时间
  143. if (entityInfo.PropertyName == nameof(BaseEntity.UpdateTime))
  144. entityInfo.SetValue(DateTime.Now);
  145. //更新人
  146. if (App.User != null)
  147. {
  148. if (entityInfo.PropertyName == nameof(BaseEntity.UpdateUserId))
  149. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.USER_ID)?.Value);
  150. if (entityInfo.PropertyName == nameof(BaseEntity.UpdateUser))
  151. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.ACCOUNT)?.Value);
  152. }
  153. }
  154. };
  155. //查询数据转换
  156. db.Aop.DataExecuted = (value, entity) =>
  157. {
  158. };
  159. }
  160. /// <summary>
  161. /// 实体更多配置
  162. /// </summary>
  163. /// <param name="db">db</param>
  164. /// <param name="dbType">数据库类型</param>
  165. private static void MoreSetting(SqlSugarScopeProvider db, DbType dbType)
  166. {
  167. db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings
  168. {
  169. SqlServerCodeFirstNvarchar = dbType == DbType.SqlServer//设置默认nvarchar
  170. };
  171. }
  172. /// <summary>
  173. /// 过滤器设置
  174. /// </summary>
  175. /// <param name="db"></param>
  176. public static void FilterSetting(SqlSugarScopeProvider db)
  177. {
  178. // 假删除过滤器
  179. //LogicDeletedEntityFilter(db);
  180. }
  181. /// <summary>
  182. /// 假删除过滤器
  183. /// </summary>
  184. /// <param name="db"></param>
  185. private static void LogicDeletedEntityFilter(SqlSugarScopeProvider db)
  186. {
  187. }
  188. private static void WriteSqlLog(string msg)
  189. {
  190. Console.WriteLine($"=============={msg}==============");
  191. }
  192. }