SqlSugarSetup.cs 16 KB

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