SqlSugarSetup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. namespace Admin.NET.Core;
  2. public static class SqlSugarSetup
  3. {
  4. /// <summary>
  5. /// Sqlsugar 上下文初始化
  6. /// </summary>
  7. /// <param name="services"></param>
  8. public static void AddSqlSugar(this IServiceCollection services)
  9. {
  10. var dbOptions = App.GetOptions<DbConnectionOptions>();
  11. var configureExternalServices = new ConfigureExternalServices
  12. {
  13. EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
  14. {
  15. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  16. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  17. column.IsNullable = true;
  18. },
  19. DataInfoCacheService = new SqlSugarCache(),
  20. };
  21. dbOptions.ConnectionConfigs.ForEach(config =>
  22. {
  23. config.ConfigureExternalServices = configureExternalServices;
  24. config.InitKeyType = InitKeyType.Attribute;
  25. config.IsAutoCloseConnection = true;
  26. config.MoreSettings = new ConnMoreSettings
  27. {
  28. IsAutoRemoveDataCache = true
  29. };
  30. });
  31. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), client =>
  32. {
  33. dbOptions.ConnectionConfigs.ForEach(config =>
  34. {
  35. var db = client.GetConnectionScope((string)config.ConfigId);
  36. // 设置超时时间
  37. db.Ado.CommandTimeOut = 30;
  38. // 打印SQL语句
  39. db.Aop.OnLogExecuting = (sql, pars) =>
  40. {
  41. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  42. Console.ForegroundColor = ConsoleColor.Green;
  43. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  44. Console.ForegroundColor = ConsoleColor.White;
  45. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  46. Console.ForegroundColor = ConsoleColor.Blue;
  47. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
  48. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  49. };
  50. db.Aop.OnError = (ex) =>
  51. {
  52. Console.ForegroundColor = ConsoleColor.Red;
  53. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  54. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  55. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  56. };
  57. // 数据审计
  58. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  59. {
  60. // 新增操作
  61. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  62. {
  63. // 主键(long类型)且没有值的---赋值雪花Id
  64. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  65. {
  66. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  67. if (id == null || (long)id == 0)
  68. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  69. }
  70. if (entityInfo.PropertyName == "CreateTime")
  71. entityInfo.SetValue(DateTime.Now);
  72. if (App.User != null)
  73. {
  74. if (entityInfo.PropertyName == "TenantId")
  75. {
  76. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  77. if (tenantId == null || tenantId == 0)
  78. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  79. }
  80. if (entityInfo.PropertyName == "CreateUserId")
  81. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  82. if (entityInfo.PropertyName == "CreateOrgId")
  83. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  84. }
  85. }
  86. // 更新操作
  87. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  88. {
  89. if (entityInfo.PropertyName == "UpdateTime")
  90. entityInfo.SetValue(DateTime.Now);
  91. if (entityInfo.PropertyName == "UpdateUserId")
  92. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  93. }
  94. };
  95. // 差异日志
  96. db.Aop.OnDiffLogEvent = async u =>
  97. {
  98. if (!config.EnableDiffLog) return;
  99. var LogDiff = new SysLogDiff
  100. {
  101. // 操作后记录(字段描述、列名、值、表名、表描述)
  102. AfterData = JsonConvert.SerializeObject(u.AfterData),
  103. // 操作前记录(字段描述、列名、值、表名、表描述)
  104. BeforeData = JsonConvert.SerializeObject(u.BeforeData),
  105. // 传进来的对象
  106. BusinessData = JsonConvert.SerializeObject(u.BusinessData),
  107. // 枚举(insert、update、delete)
  108. DiffType = u.DiffType.ToString(),
  109. Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  110. Parameters = JsonConvert.SerializeObject(u.Parameters),
  111. Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  112. };
  113. await client.GetConnectionScope(SqlSugarConst.ConfigId).Insertable(LogDiff).ExecuteCommandAsync();
  114. Console.ForegroundColor = ConsoleColor.Red;
  115. Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{JsonConvert.SerializeObject(LogDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
  116. };
  117. // 缓存处理过滤器
  118. var queryFilterProvider = db.DataCache.Get<QueryFilterProvider>(config.ConfigId);
  119. if (queryFilterProvider == null)
  120. {
  121. // 配置实体假删除过滤器
  122. SetDeletedEntityFilter(db);
  123. // 配置实体机构过滤器
  124. SetOrgEntityFilter(db);
  125. // 配置自定义实体过滤器
  126. SetCustomEntityFilter(db);
  127. // 配置租户实体过滤器
  128. SetTenantEntityFilter(db);
  129. db.DataCache.Add(config.ConfigId, db.QueryFilter);
  130. }
  131. else
  132. {
  133. db.QueryFilter = queryFilterProvider;
  134. }
  135. });
  136. });
  137. // 初始化数据库表结构及种子数据
  138. InitDataBase(sqlSugar, dbOptions);
  139. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  140. services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
  141. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 注册事务与工作单元
  142. }
  143. /// <summary>
  144. /// 初始化数据库结构
  145. /// </summary>
  146. private static void InitDataBase(SqlSugarScope db, DbConnectionOptions dbOptions)
  147. {
  148. // 创建数据库
  149. dbOptions.ConnectionConfigs.ForEach(config =>
  150. {
  151. if (!config.EnableInitDb) return;
  152. if (config.DbType == SqlSugar.DbType.Oracle) return;
  153. db.GetConnectionScope(config.ConfigId).DbMaintenance.CreateDatabase();
  154. });
  155. // 获取所有实体表-初始化表结构
  156. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  157. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
  158. if (!entityTypes.Any()) return;
  159. foreach (var entityType in entityTypes)
  160. {
  161. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  162. var configId = tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId.ToString();
  163. if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId.ToString()).EnableInitDb)
  164. continue;
  165. var db2 = db.GetConnectionScope(configId);
  166. db2.CodeFirst.InitTables(entityType);
  167. }
  168. // 获取所有种子配置-初始化数据
  169. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  170. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  171. if (!seedDataTypes.Any()) return;
  172. foreach (var seedType in seedDataTypes)
  173. {
  174. var instance = Activator.CreateInstance(seedType);
  175. var hasDataMethod = seedType.GetMethod("HasData");
  176. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  177. if (seedData == null) continue;
  178. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  179. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  180. var configId = tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId.ToString();
  181. if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb)
  182. continue;
  183. var db2 = db.GetConnectionScope(configId);
  184. var seedDataTable = seedData.ToList().ToDataTable();
  185. seedDataTable.TableName = db.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  186. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  187. {
  188. var storage = db2.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  189. storage.AsInsertable.ExecuteCommand();
  190. storage.AsUpdateable.ExecuteCommand();
  191. }
  192. else // 没有主键或者不是预定义的主键(没主键有重复的可能)
  193. {
  194. var storage = db2.Storageable(seedDataTable).ToStorage();
  195. storage.AsInsertable.ExecuteCommand();
  196. }
  197. }
  198. }
  199. /// <summary>
  200. /// 配置实体假删除过滤器
  201. /// </summary>
  202. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  203. {
  204. // 获取所有继承基类数据表集合
  205. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  206. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  207. if (!entityTypes.Any()) return;
  208. foreach (var entityType in entityTypes)
  209. {
  210. // 排除非当前数据库实体
  211. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  212. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  213. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  214. continue;
  215. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  216. db.QueryFilter.Add(new TableFilterItem<object>(entityType, dynamicExpression));
  217. }
  218. }
  219. /// <summary>
  220. /// 配置实体机构过滤器
  221. /// </summary>
  222. private static async void SetOrgEntityFilter(SqlSugarScopeProvider db)
  223. {
  224. // 获取业务数据表集合
  225. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  226. && u.BaseType == typeof(DataEntityBase));
  227. if (!dataEntityTypes.Any()) return;
  228. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  229. if (string.IsNullOrWhiteSpace(userId)) return;
  230. // 获取用户机构Id集合
  231. var orgIds = await App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  232. if (orgIds == null || orgIds.Count == 0) return;
  233. foreach (var dataEntityType in dataEntityTypes)
  234. {
  235. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  236. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  237. }
  238. }
  239. /// <summary>
  240. /// 配置自定义实体过滤器
  241. /// </summary>
  242. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  243. {
  244. // 排除超管过滤
  245. if (App.User?.FindFirst(ClaimConst.SuperAdmin)?.Value == ((int)UserTypeEnum.SuperAdmin).ToString())
  246. return;
  247. // 获取继承自定义实体过滤器接口的类集合
  248. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  249. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  250. if (!entityFilterTypes.Any()) return;
  251. foreach (var entityFilter in entityFilterTypes)
  252. {
  253. var instance = Activator.CreateInstance(entityFilter);
  254. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  255. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  256. if (entityFilters == null) continue;
  257. foreach (TableFilterItem<object> filter in entityFilters)
  258. db.QueryFilter.Add(filter);
  259. }
  260. }
  261. /// <summary>
  262. /// 配置租户实体过滤器
  263. /// </summary>
  264. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  265. {
  266. // 获取租户实体数据表集合
  267. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  268. && u.BaseType == typeof(EntityTenant));
  269. if (!dataEntityTypes.Any()) return;
  270. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  271. if (string.IsNullOrWhiteSpace(tenantId)) return;
  272. foreach (var dataEntityType in dataEntityTypes)
  273. {
  274. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  275. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  276. }
  277. }
  278. }