SqlSugarSetup.cs 25 KB

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