SqlSugarSetup.cs 20 KB

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