SqlSugarSetup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. dbOptions.ConnectionConfigs.ForEach(config =>
  12. {
  13. SetDbConfig(config);
  14. });
  15. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  16. {
  17. dbOptions.ConnectionConfigs.ForEach(config =>
  18. {
  19. SetDbAop(db.GetConnectionScope(config.ConfigId));
  20. });
  21. });
  22. // 初始化数据库表结构及种子数据
  23. dbOptions.ConnectionConfigs.ForEach(config =>
  24. {
  25. InitDatabase(sqlSugar, config);
  26. });
  27. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  28. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  29. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  30. }
  31. /// <summary>
  32. /// 配置连接属性
  33. /// </summary>
  34. /// <param name="config"></param>
  35. public static void SetDbConfig(DbConnectionConfig config)
  36. {
  37. var configureExternalServices = new ConfigureExternalServices
  38. {
  39. EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
  40. {
  41. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  42. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  43. column.IsNullable = true;
  44. },
  45. DataInfoCacheService = new SqlSugarCache(),
  46. };
  47. config.ConfigureExternalServices = configureExternalServices;
  48. config.InitKeyType = InitKeyType.Attribute;
  49. config.IsAutoCloseConnection = true;
  50. config.MoreSettings = new ConnMoreSettings
  51. {
  52. IsAutoRemoveDataCache = true
  53. };
  54. }
  55. /// <summary>
  56. /// 配置Aop
  57. /// </summary>
  58. /// <param name="db"></param>
  59. public static void SetDbAop(SqlSugarScopeProvider db)
  60. {
  61. var config = db.CurrentConnectionConfig;
  62. // 设置超时时间
  63. db.Ado.CommandTimeOut = 30;
  64. // 打印SQL语句
  65. db.Aop.OnLogExecuting = (sql, pars) =>
  66. {
  67. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  68. Console.ForegroundColor = ConsoleColor.Green;
  69. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  70. Console.ForegroundColor = ConsoleColor.White;
  71. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  72. Console.ForegroundColor = ConsoleColor.Blue;
  73. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
  74. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  75. };
  76. db.Aop.OnError = (ex) =>
  77. {
  78. if (ex.Parametres == null) return;
  79. Console.ForegroundColor = ConsoleColor.Red;
  80. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  81. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  82. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  83. };
  84. // 数据审计
  85. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  86. {
  87. // 新增操作
  88. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  89. {
  90. // 主键(long类型)且没有值的---赋值雪花Id
  91. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  92. {
  93. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  94. if (id == null || (long)id == 0)
  95. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  96. }
  97. if (entityInfo.PropertyName == "CreateTime")
  98. entityInfo.SetValue(DateTime.Now);
  99. if (App.User != null)
  100. {
  101. if (entityInfo.PropertyName == "TenantId")
  102. {
  103. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  104. if (tenantId == null || tenantId == 0)
  105. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  106. }
  107. if (entityInfo.PropertyName == "CreateUserId")
  108. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  109. if (entityInfo.PropertyName == "CreateOrgId")
  110. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  111. }
  112. }
  113. // 更新操作
  114. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  115. {
  116. if (entityInfo.PropertyName == "UpdateTime")
  117. entityInfo.SetValue(DateTime.Now);
  118. if (entityInfo.PropertyName == "UpdateUserId")
  119. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  120. }
  121. };
  122. //// 差异日志
  123. //db.Aop.OnDiffLogEvent = async u =>
  124. //{
  125. // if (!config.EnableDiffLog) return;
  126. // var LogDiff = new SysLogDiff
  127. // {
  128. // // 操作后记录(字段描述、列名、值、表名、表描述)
  129. // AfterData = JsonConvert.SerializeObject(u.AfterData),
  130. // // 操作前记录(字段描述、列名、值、表名、表描述)
  131. // BeforeData = JsonConvert.SerializeObject(u.BeforeData),
  132. // // 传进来的对象
  133. // BusinessData = JsonConvert.SerializeObject(u.BusinessData),
  134. // // 枚举(insert、update、delete)
  135. // DiffType = u.DiffType.ToString(),
  136. // Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  137. // Parameters = JsonConvert.SerializeObject(u.Parameters),
  138. // Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  139. // };
  140. // await db.AsTenant().GetConnectionScope(SqlSugarConst.ConfigId).Insertable(LogDiff).ExecuteCommandAsync();
  141. // Console.ForegroundColor = ConsoleColor.Red;
  142. // Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{JsonConvert.SerializeObject(LogDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
  143. //};
  144. // 超管时排除各种过滤器
  145. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  146. return;
  147. // 配置实体假删除过滤器
  148. SetDeletedEntityFilter(db);
  149. // 配置租户过滤器
  150. SetTenantEntityFilter(db);
  151. // 配置用户机构范围过滤器
  152. SetOrgEntityFilter(db);
  153. // 配置自定义过滤器
  154. SetCustomEntityFilter(db);
  155. }
  156. /// <summary>
  157. /// 初始化数据库
  158. /// </summary>
  159. /// <param name="db"></param>
  160. /// <param name="config"></param>
  161. public static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  162. {
  163. if (!config.EnableInitDb || config.DbType == SqlSugar.DbType.Oracle) return;
  164. // 创建数据库
  165. db.DbMaintenance.CreateDatabase();
  166. // 获取所有实体表-初始化表结构
  167. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  168. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
  169. if (!entityTypes.Any()) return;
  170. var db2 = db.GetConnectionScope(config.ConfigId);
  171. foreach (var entityType in entityTypes)
  172. {
  173. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  174. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  175. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId) continue;
  176. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  177. if (splitTable == null)
  178. db2.CodeFirst.InitTables(entityType);
  179. else
  180. db2.CodeFirst.SplitTables().InitTables(entityType);
  181. }
  182. // 获取所有种子配置-初始化数据
  183. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  184. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  185. if (!seedDataTypes.Any()) return;
  186. foreach (var seedType in seedDataTypes)
  187. {
  188. var instance = Activator.CreateInstance(seedType);
  189. var hasDataMethod = seedType.GetMethod("HasData");
  190. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  191. if (seedData == null) continue;
  192. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  193. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  194. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  195. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId) continue;
  196. var seedDataTable = seedData.ToList().ToDataTable();
  197. seedDataTable.TableName = db2.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  198. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  199. {
  200. var storage = db2.CopyNew().Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  201. storage.AsInsertable.ExecuteCommand();
  202. var ignoreUpdate = hasDataMethod.GetCustomAttribute<IgnoreUpdateAttribute>();
  203. if (ignoreUpdate == null) storage.AsUpdateable.ExecuteCommand();
  204. }
  205. else // 没有主键或者不是预定义的主键(有重复的可能)
  206. {
  207. var storage = db2.CopyNew().Storageable(seedDataTable).ToStorage();
  208. storage.AsInsertable.ExecuteCommand();
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// 初始化租户库连接
  214. /// </summary>
  215. /// <param name="iTenant"></param>
  216. /// <param name="tenantId"></param>
  217. public static SqlSugarScopeProvider InitTenantConnection(ITenant iTenant, long tenantId)
  218. {
  219. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
  220. if (!iTenant.IsAnyConnection(tenantId.ToString()))
  221. {
  222. iTenant.AddConnection(new ConnectionConfig()
  223. {
  224. ConfigId = tenantId.ToString(),
  225. ConnectionString = tenant.Connection,
  226. DbType = tenant.DbType,
  227. IsAutoCloseConnection = true
  228. });
  229. SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  230. }
  231. return iTenant.GetConnectionScope(tenantId.ToString());
  232. }
  233. /// <summary>
  234. /// 初始化租户业务数据库
  235. /// </summary>
  236. /// <param name="itenant"></param>
  237. /// <param name="config"></param>
  238. public static void InitTenantDatabase(ITenant itenant, DbConnectionConfig config)
  239. {
  240. SetDbConfig(config);
  241. itenant.AddConnection(config);
  242. var db = itenant.GetConnectionScope(config.ConfigId);
  243. db.DbMaintenance.CreateDatabase();
  244. // 获取所有实体表-初始化租户业务表
  245. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  246. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false)
  247. && u.IsDefined(typeof(TenantBusinessAttribute), false));
  248. if (!entityTypes.Any()) return;
  249. foreach (var entityType in entityTypes)
  250. {
  251. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  252. if (splitTable == null)
  253. db.CodeFirst.InitTables(entityType);
  254. else
  255. db.CodeFirst.SplitTables().InitTables(entityType);
  256. }
  257. }
  258. /// <summary>
  259. /// 配置实体假删除过滤器
  260. /// </summary>
  261. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  262. {
  263. // 配置实体假删除缓存
  264. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:IsDelete";
  265. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  266. if (tableFilterItemList == null)
  267. {
  268. // 获取基类实体数据表
  269. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  270. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  271. if (!entityTypes.Any()) return;
  272. var tableFilterItems = new List<TableFilterItem<object>>();
  273. foreach (var entityType in entityTypes)
  274. {
  275. // 排除非当前数据库实体
  276. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  277. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  278. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  279. continue;
  280. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  281. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  282. tableFilterItems.Add(tableFilterItem);
  283. db.QueryFilter.Add(tableFilterItem);
  284. }
  285. db.DataCache.Add(cacheKey, tableFilterItems);
  286. }
  287. else
  288. {
  289. tableFilterItemList.ForEach(u =>
  290. {
  291. db.QueryFilter.Add(u);
  292. });
  293. }
  294. }
  295. /// <summary>
  296. /// 配置租户过滤器
  297. /// </summary>
  298. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  299. {
  300. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  301. if (string.IsNullOrWhiteSpace(tenantId)) return;
  302. // 配置租户缓存
  303. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:TenantId:{tenantId}";
  304. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  305. if (tableFilterItemList == null)
  306. {
  307. // 获取租户实体数据表
  308. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  309. && u.BaseType == typeof(EntityTenant));
  310. if (!entityTypes.Any()) return;
  311. var tableFilterItems = new List<TableFilterItem<object>>();
  312. foreach (var entityType in entityTypes)
  313. {
  314. // 排除非当前数据库实体
  315. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  316. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  317. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  318. continue;
  319. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  320. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  321. tableFilterItems.Add(tableFilterItem);
  322. db.QueryFilter.Add(tableFilterItem);
  323. }
  324. db.DataCache.Add(cacheKey, tableFilterItems);
  325. }
  326. else
  327. {
  328. tableFilterItemList.ForEach(u =>
  329. {
  330. db.QueryFilter.Add(u);
  331. });
  332. }
  333. }
  334. /// <summary>
  335. /// 配置用户机构范围过滤器
  336. /// </summary>
  337. private static void SetOrgEntityFilter(SqlSugarScopeProvider db)
  338. {
  339. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  340. if (string.IsNullOrWhiteSpace(userId)) return;
  341. // 配置用户机构范围缓存
  342. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:UserId:{userId}";
  343. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  344. if (tableFilterItemList == null)
  345. {
  346. // 获取用户所属机构
  347. var orgIds = App.GetService<SysCacheService>().Get<List<long>>(CacheConst.KeyOrgIdList + userId);
  348. if (orgIds == null || orgIds.Count == 0) return;
  349. // 获取业务实体数据表
  350. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  351. && u.BaseType == typeof(DataEntityBase));
  352. if (!entityTypes.Any()) return;
  353. var tableFilterItems = new List<TableFilterItem<object>>();
  354. foreach (var entityType in entityTypes)
  355. {
  356. // 排除非当前数据库实体
  357. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  358. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  359. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  360. continue;
  361. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  362. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  363. tableFilterItems.Add(tableFilterItem);
  364. db.QueryFilter.Add(tableFilterItem);
  365. }
  366. db.DataCache.Add(cacheKey, tableFilterItems);
  367. }
  368. else
  369. {
  370. tableFilterItemList.ForEach(u =>
  371. {
  372. db.QueryFilter.Add(u);
  373. });
  374. }
  375. }
  376. /// <summary>
  377. /// 配置自定义过滤器
  378. /// </summary>
  379. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  380. {
  381. // 配置用户机构范围缓存
  382. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:Custom";
  383. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  384. if (tableFilterItemList == null)
  385. {
  386. // 获取自定义实体过滤器
  387. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  388. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  389. if (!entityFilterTypes.Any()) return;
  390. var tableFilterItems = new List<TableFilterItem<object>>();
  391. foreach (var entityFilter in entityFilterTypes)
  392. {
  393. var instance = Activator.CreateInstance(entityFilter);
  394. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  395. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  396. if (entityFilters == null) continue;
  397. foreach (var u in entityFilters)
  398. {
  399. var tableFilterItem = (TableFilterItem<object>)u;
  400. var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
  401. // 排除非当前数据库实体
  402. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  403. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  404. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  405. return;
  406. tableFilterItems.Add(tableFilterItem);
  407. db.QueryFilter.Add(tableFilterItem);
  408. }
  409. }
  410. db.DataCache.Add(cacheKey, tableFilterItems);
  411. }
  412. else
  413. {
  414. tableFilterItemList.ForEach(u =>
  415. {
  416. db.QueryFilter.Add(u);
  417. });
  418. }
  419. }
  420. }