平安校园
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

DbContext.cs 8.0 KiB

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