SqlSugarSetup.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using DbType = SqlSugar.DbType;
  7. namespace Admin.NET.Core;
  8. public static class SqlSugarSetup
  9. {
  10. // 多租户实例
  11. public static ITenant ITenant { get; set; }
  12. // 是否正在处理种子数据
  13. private static bool _isHandlingSeedData = false;
  14. /// <summary>
  15. /// SqlSugar 上下文初始化
  16. /// </summary>
  17. /// <param name="services"></param>
  18. public static void AddSqlSugar(this IServiceCollection services)
  19. {
  20. // 注册雪花Id
  21. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  22. YitIdHelper.SetIdGenerator(snowIdOpt);
  23. // 自定义 SqlSugar 雪花ID算法
  24. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  25. StaticConfig.CustomSnowFlakeFunc = () =>
  26. {
  27. return YitIdHelper.NextId();
  28. };
  29. // 动态表达式 SqlFunc 支持,https://www.donet5.com/Home/Doc?typeId=2569
  30. StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser);
  31. StaticConfig.DynamicExpressionParsingConfig = new ParsingConfig
  32. {
  33. CustomTypeProvider = new SqlSugarTypeProvider()
  34. };
  35. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  36. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  37. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  38. {
  39. dbOptions.ConnectionConfigs.ForEach(config =>
  40. {
  41. var dbProvider = db.GetConnectionScope(config.ConfigId);
  42. SetDbAop(dbProvider, dbOptions.EnableConsoleSql, dbOptions.SuperAdminIgnoreIDeletedFilter);
  43. SetDbDiffLog(dbProvider, config);
  44. });
  45. });
  46. ITenant = sqlSugar;
  47. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  48. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  49. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  50. // 初始化数据库表结构及种子数据
  51. dbOptions.ConnectionConfigs.ForEach(config =>
  52. {
  53. InitDatabase(sqlSugar, config);
  54. });
  55. }
  56. /// <summary>
  57. /// 配置连接属性
  58. /// </summary>
  59. /// <param name="config"></param>
  60. public static void SetDbConfig(DbConnectionConfig config)
  61. {
  62. if (config.DbSettings.EnableConnStringEncrypt)
  63. config.ConnectionString = CryptogramUtil.Decrypt(config.ConnectionString);
  64. var configureExternalServices = new ConfigureExternalServices
  65. {
  66. EntityNameService = (type, entity) => // 处理表
  67. {
  68. entity.IsDisabledDelete = true; // 禁止删除非 sqlsugar 创建的列
  69. // 只处理贴了特性[SugarTable]表
  70. if (!type.GetCustomAttributes<SugarTable>().Any())
  71. return;
  72. if (config.DbSettings.EnableUnderLine && !entity.DbTableName.Contains('_'))
  73. entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); // 驼峰转下划线
  74. },
  75. EntityService = (type, column) => // 处理列
  76. {
  77. // 只处理贴了特性[SugarColumn]列
  78. if (!type.GetCustomAttributes<SugarColumn>().Any())
  79. return;
  80. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  81. column.IsNullable = true;
  82. if (config.DbSettings.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  83. column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); // 驼峰转下划线
  84. },
  85. DataInfoCacheService = new SqlSugarCache(),
  86. };
  87. config.ConfigureExternalServices = configureExternalServices;
  88. config.InitKeyType = InitKeyType.Attribute;
  89. config.IsAutoCloseConnection = true;
  90. config.MoreSettings = new ConnMoreSettings
  91. {
  92. IsAutoRemoveDataCache = true, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  93. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  94. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  95. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  96. };
  97. // 若库类型是人大金仓则默认设置PG模式
  98. if (config.DbType == DbType.Kdbndp)
  99. config.MoreSettings.DatabaseModel = DbType.PostgreSQL; // 配置PG模式主要是兼容系统表差异
  100. // 若库类型是Oracle则默认主键名字和参数名字最大长度
  101. if (config.DbType == DbType.Oracle)
  102. config.MoreSettings.MaxParameterNameLength = 30;
  103. }
  104. /// <summary>
  105. /// 配置Aop
  106. /// </summary>
  107. /// <param name="db"></param>
  108. /// <param name="enableConsoleSql"></param>
  109. /// <param name="superAdminIgnoreIDeletedFilter"></param>
  110. public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql, bool superAdminIgnoreIDeletedFilter)
  111. {
  112. // 设置超时时间
  113. db.Ado.CommandTimeOut = 30;
  114. // 打印SQL语句
  115. if (enableConsoleSql)
  116. {
  117. db.Aop.OnLogExecuting = (sql, pars) =>
  118. {
  119. //// 若参数值超过100个字符则进行截取
  120. //foreach (var par in pars)
  121. //{
  122. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  123. // if (par.Value.ToString().Length > 100)
  124. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  125. //}
  126. var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
  127. var originColor = Console.ForegroundColor;
  128. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  129. Console.ForegroundColor = ConsoleColor.Green;
  130. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  131. Console.ForegroundColor = ConsoleColor.Yellow;
  132. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  133. Console.ForegroundColor = ConsoleColor.Red;
  134. Console.WriteLine(log);
  135. Console.ForegroundColor = originColor;
  136. App.PrintToMiniProfiler("SqlSugar", "Info", log);
  137. };
  138. }
  139. db.Aop.OnError = ex =>
  140. {
  141. if (ex.Parametres == null) return;
  142. var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
  143. Log.Error(log, ex);
  144. App.PrintToMiniProfiler("SqlSugar", "Error", log);
  145. };
  146. db.Aop.OnLogExecuted = (sql, pars) =>
  147. {
  148. //// 若参数值超过100个字符则进行截取
  149. //foreach (var par in pars)
  150. //{
  151. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  152. // if (par.Value.ToString().Length > 100)
  153. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  154. //}
  155. // 执行时间超过5秒时
  156. if (!(db.Ado.SqlExecutionTime.TotalSeconds > 5)) return;
  157. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  158. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  159. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  160. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetNativeSql(sql, pars)}";
  161. Log.Warning(log);
  162. App.PrintToMiniProfiler("SqlSugar", "Slow", log);
  163. };
  164. // 数据审计
  165. db.Aop.DataExecuting = (_, entityInfo) =>
  166. {
  167. // 若正在处理种子数据则直接返回
  168. if (_isHandlingSeedData) return;
  169. // 新增/插入
  170. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  171. {
  172. // 若主键是长整型且空则赋值雪花Id
  173. if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  174. {
  175. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  176. if (id == null || (long)id == 0)
  177. entityInfo.SetValue(YitIdHelper.NextId());
  178. }
  179. // 若创建时间为空则赋值当前时间
  180. else if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  181. {
  182. var createTime = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
  183. if (createTime == null || createTime.Equals(DateTime.MinValue))
  184. entityInfo.SetValue(DateTime.Now);
  185. }
  186. // 若当前用户为空(非web线程时)
  187. if (App.User == null) return;
  188. dynamic entityValue = entityInfo.EntityValue;
  189. if (entityInfo.PropertyName == nameof(EntityBaseTenantId.TenantId))
  190. {
  191. var tenantId = entityValue.TenantId;
  192. if (tenantId == null || tenantId == 0)
  193. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  194. }
  195. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  196. {
  197. var createUserId = entityValue.CreateUserId;
  198. if (createUserId == 0 || createUserId == null)
  199. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  200. }
  201. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  202. {
  203. var createUserName = entityValue.CreateUserName;
  204. if (string.IsNullOrEmpty(createUserName))
  205. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  206. }
  207. else if (entityInfo.PropertyName == "CreateOrgId")
  208. {
  209. var createOrgId = entityValue.CreateOrgId;
  210. if (createOrgId == 0 || createOrgId == null)
  211. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  212. }
  213. else if (entityInfo.PropertyName == "CreateOrgName")
  214. {
  215. var createOrgName = entityValue.CreateOrgName;
  216. if (string.IsNullOrEmpty(createOrgName))
  217. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  218. }
  219. }
  220. // 编辑/更新
  221. else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  222. {
  223. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  224. entityInfo.SetValue(DateTime.Now);
  225. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  226. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  227. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  228. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  229. }
  230. };
  231. // 是否为超级管理员
  232. var isSuperAdmin = App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString();
  233. // 配置假删除过滤器,如果当前用户是超级管理员并且允许忽略软删除过滤器则不会应用
  234. if (!isSuperAdmin || !superAdminIgnoreIDeletedFilter)
  235. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  236. // 超管排除其他过滤器
  237. if (isSuperAdmin) return;
  238. // 配置租户过滤器
  239. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  240. if (!string.IsNullOrWhiteSpace(tenantId))
  241. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  242. // 配置用户机构(数据范围)过滤器
  243. SqlSugarFilter.SetOrgEntityFilter(db);
  244. // 配置自定义过滤器
  245. SqlSugarFilter.SetCustomEntityFilter(db);
  246. }
  247. /// <summary>
  248. /// 开启库表差异化日志
  249. /// </summary>
  250. /// <param name="db"></param>
  251. /// <param name="config"></param>
  252. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  253. {
  254. if (!config.DbSettings.EnableDiffLog) return;
  255. async void AopOnDiffLogEvent(DiffLogModel u)
  256. {
  257. // 记录差异数据
  258. var diffData = new List<dynamic>();
  259. for (int i = 0; i < u.AfterData.Count; i++)
  260. {
  261. var diffColumns = new List<dynamic>();
  262. var afterColumns = u.AfterData[i].Columns;
  263. var beforeColumns = u.BeforeData[i].Columns;
  264. for (int j = 0; j < afterColumns.Count; j++)
  265. {
  266. if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
  267. diffColumns.Add(new
  268. {
  269. afterColumns[j].IsPrimaryKey,
  270. afterColumns[j].ColumnName,
  271. afterColumns[j].ColumnDescription,
  272. BeforeValue = beforeColumns[j].Value,
  273. AfterValue = afterColumns[j].Value,
  274. });
  275. }
  276. diffData.Add(new { u.AfterData[i].TableName, u.AfterData[i].TableDescription, Columns = diffColumns });
  277. }
  278. var logDiff = new SysLogDiff
  279. {
  280. // 差异数据(字段描述、列名、值、表名、表描述)
  281. DiffData = JSON.Serialize(diffData),
  282. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  283. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  284. // 枚举(insert、update、delete)
  285. DiffType = u.DiffType.ToString(),
  286. Sql = u.Sql,
  287. Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
  288. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  289. };
  290. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  291. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  292. Console.ForegroundColor = ConsoleColor.Red;
  293. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  294. }
  295. db.Aop.OnDiffLogEvent = AopOnDiffLogEvent;
  296. }
  297. /// <summary>
  298. /// 初始化数据库
  299. /// </summary>
  300. /// <param name="db">SqlSugarScope 实例</param>
  301. /// <param name="config">数据库连接配置</param>
  302. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  303. {
  304. var dbProvider = db.GetConnectionScope(config.ConfigId);
  305. // 初始化数据库
  306. if (config.DbSettings.EnableInitDb)
  307. {
  308. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  309. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  310. }
  311. // 初始化表结构
  312. if (config.TableSettings.EnableInitTable)
  313. {
  314. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  315. var entityTypes = GetEntityTypesForInit(config);
  316. InitializeTables(dbProvider, entityTypes, config);
  317. }
  318. // 初始化种子数据
  319. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  320. }
  321. /// <summary>
  322. /// 获取需要初始化的实体类型
  323. /// </summary>
  324. /// <param name="config">数据库连接配置</param>
  325. /// <returns>实体类型列表</returns>
  326. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  327. {
  328. return App.EffectiveTypes
  329. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  330. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  331. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  332. .Where(u => IsEntityForConfig(u, config))
  333. .ToList();
  334. }
  335. /// <summary>
  336. /// 判断实体是否属于当前配置
  337. /// </summary>
  338. /// <param name="entityType">实体类型</param>
  339. /// <param name="config">数据库连接配置</param>
  340. /// <returns>是否属于当前配置</returns>
  341. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  342. {
  343. switch (config.ConfigId.ToString())
  344. {
  345. case SqlSugarConst.MainConfigId:
  346. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  347. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  348. !entityType.GetCustomAttributes<TenantAttribute>().Any());
  349. case SqlSugarConst.LogConfigId:
  350. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  351. default:
  352. {
  353. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  354. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// 初始化表结构
  360. /// </summary>
  361. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  362. /// <param name="entityTypes">实体类型列表</param>
  363. /// <param name="config">数据库连接配置</param>
  364. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  365. {
  366. int count = 0, sum = entityTypes.Count;
  367. var tasks = entityTypes.Select(entityType => Task.Run(() =>
  368. {
  369. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  370. UpdateNullableColumns(dbProvider, entityType);
  371. InitializeTable(dbProvider, entityType);
  372. }));
  373. Task.WhenAll(tasks).GetAwaiter().GetResult();
  374. }
  375. /// <summary>
  376. /// 更新表中不存在于实体的字段为可空
  377. /// </summary>
  378. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  379. /// <param name="entityType">实体类型</param>
  380. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  381. {
  382. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  383. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  384. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  385. {
  386. dbColumn.IsNullable = true;
  387. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  388. }
  389. }
  390. /// <summary>
  391. /// 初始化表
  392. /// </summary>
  393. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  394. /// <param name="entityType">实体类型</param>
  395. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType)
  396. {
  397. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  398. {
  399. dbProvider.CodeFirst.InitTables(entityType);
  400. }
  401. else
  402. {
  403. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  404. }
  405. }
  406. /// <summary>
  407. /// 初始化种子数据
  408. /// </summary>
  409. /// <param name="db">SqlSugarScope 实例</param>
  410. /// <param name="config">数据库连接配置</param>
  411. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  412. {
  413. var dbProvider = db.GetConnectionScope(config.ConfigId);
  414. _isHandlingSeedData = true;
  415. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  416. var seedDataTypes = GetSeedDataTypes(config);
  417. int count = 0, sum = seedDataTypes.Count;
  418. var tasks = seedDataTypes.Select(seedType => Task.Run(() =>
  419. {
  420. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  421. if (!IsEntityForConfig(entityType, config)) return;
  422. var seedData = GetSeedData(seedType);
  423. if (seedData == null) return;
  424. AdjustSeedDataIds(seedData, config);
  425. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  426. }));
  427. Task.WhenAll(tasks).GetAwaiter().GetResult();
  428. _isHandlingSeedData = false;
  429. }
  430. /// <summary>
  431. /// 获取种子数据类型
  432. /// </summary>
  433. /// <param name="config">数据库连接配置</param>
  434. /// <returns>种子数据类型列表</returns>
  435. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  436. {
  437. return App.EffectiveTypes
  438. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  439. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  440. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  441. .ToList();
  442. }
  443. /// <summary>
  444. /// 获取种子数据
  445. /// </summary>
  446. /// <param name="seedType">种子数据类型</param>
  447. /// <returns>种子数据列表</returns>
  448. private static IEnumerable<object> GetSeedData(Type seedType)
  449. {
  450. var instance = Activator.CreateInstance(seedType);
  451. var hasDataMethod = seedType.GetMethod("HasData");
  452. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  453. }
  454. /// <summary>
  455. /// 调整种子数据的 ID
  456. /// </summary>
  457. /// <param name="seedData">种子数据列表</param>
  458. /// <param name="config">数据库连接配置</param>
  459. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  460. {
  461. var seedId = config.ConfigId.ToLong();
  462. foreach (var data in seedData)
  463. {
  464. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  465. if (idProperty == null) continue;
  466. var idValue = idProperty.GetValue(data);
  467. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  468. {
  469. idProperty.SetValue(data, ++seedId);
  470. }
  471. }
  472. }
  473. /// <summary>
  474. /// 插入或更新种子数据
  475. /// </summary>
  476. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  477. /// <param name="seedType">种子数据类型</param>
  478. /// <param name="entityType">实体类型</param>
  479. /// <param name="seedData">种子数据列表</param>
  480. /// <param name="config">数据库连接配置</param>
  481. /// <param name="count">当前处理的数量</param>
  482. /// <param name="sum">总数量</param>
  483. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  484. {
  485. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  486. var dataList = seedData.ToList();
  487. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  488. {
  489. var initMethod = seedType.GetMethod("Init");
  490. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  491. }
  492. else
  493. {
  494. int updateCount = 0, insertCount = 0;
  495. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  496. {
  497. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  498. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  499. {
  500. updateCount = storage.AsUpdateable
  501. .IgnoreColumns(entityInfo.Columns
  502. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  503. .Select(u => u.PropertyName).ToArray())
  504. .ExecuteCommand();
  505. }
  506. insertCount = storage.AsInsertable.ExecuteCommand();
  507. }
  508. else
  509. {
  510. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  511. {
  512. insertCount = dataList.Count;
  513. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  514. }
  515. }
  516. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  517. }
  518. }
  519. /// <summary>
  520. /// 初始化租户业务数据库
  521. /// </summary>
  522. /// <param name="iTenant"></param>
  523. /// <param name="config"></param>
  524. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  525. {
  526. SetDbConfig(config);
  527. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  528. iTenant.AddConnection(config);
  529. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  530. db.DbMaintenance.CreateDatabase();
  531. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  532. var entityTypes = App.EffectiveTypes
  533. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  534. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  535. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  536. if (entityTypes.Count == 0) return;
  537. foreach (var entityType in entityTypes)
  538. {
  539. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  540. if (splitTable == null)
  541. db.CodeFirst.InitTables(entityType);
  542. else
  543. db.CodeFirst.SplitTables().InitTables(entityType);
  544. }
  545. }
  546. }