SqlSugarSetup.cs 16 KB

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