SqlSugarSetup.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  66. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  67. };
  68. dbProvider.Aop.OnError = (ex) =>
  69. {
  70. Console.ForegroundColor = ConsoleColor.Red;
  71. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  72. Console.WriteLine($"{ex.Message}{Environment.NewLine}{ex.Sql}{Environment.NewLine}{pars}{Environment.NewLine}");
  73. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  74. };
  75. // 数据审计
  76. dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
  77. {
  78. // 新增操作
  79. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  80. {
  81. // 主键(long)-赋值雪花Id
  82. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  83. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  84. if (entityInfo.PropertyName == "CreateTime")
  85. entityInfo.SetValue(DateTime.Now);
  86. if (App.User != null)
  87. {
  88. if (entityInfo.PropertyName == "TenantId")
  89. {
  90. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  91. if (tenantId == null || tenantId == 0)
  92. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  93. }
  94. if (entityInfo.PropertyName == "CreateUserId")
  95. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  96. if (entityInfo.PropertyName == "CreateOrgId")
  97. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  98. }
  99. }
  100. // 更新操作
  101. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  102. {
  103. if (entityInfo.PropertyName == "UpdateTime")
  104. entityInfo.SetValue(DateTime.Now);
  105. if (entityInfo.PropertyName == "UpdateUserId")
  106. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  107. }
  108. };
  109. // 配置实体假删除过滤器
  110. SetDeletedEntityFilter(dbProvider);
  111. // 配置实体机构过滤器
  112. SetOrgEntityFilter(dbProvider);
  113. // 配置自定义实体过滤器
  114. SetCustomEntityFilter(dbProvider);
  115. // 配置租户实体过滤器
  116. SetTenantEntityFilter(dbProvider);
  117. });
  118. });
  119. // 初始化数据库结构及种子数据
  120. if (dbOptions.InitTable)
  121. InitDataBase(sqlSugar, dbOptions);
  122. return sqlSugar;
  123. });
  124. services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
  125. }
  126. /// <summary>
  127. /// 初始化数据库结构
  128. /// </summary>
  129. public static void InitDataBase(SqlSugarScope db, ConnectionStringsOptions dbOptions)
  130. {
  131. // 创建系统默认数据库
  132. db.DbMaintenance.CreateDatabase();
  133. // 创建其他业务数据库
  134. dbOptions.DbConfigs.ForEach(config =>
  135. {
  136. db.GetConnection(config.DbConfigId).DbMaintenance.CreateDatabase();
  137. });
  138. // 获取所有实体表
  139. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  140. && u.IsDefined(typeof(SqlSugarEntityAttribute), false))
  141. .OrderByDescending(u => u.GetSqlSugarEntityOrder());
  142. if (!entityTypes.Any()) return;
  143. // 初始化库表结构
  144. foreach (var entityType in entityTypes)
  145. {
  146. var dbConfigId = entityType.GetCustomAttribute<SqlSugarEntityAttribute>(true).DbConfigId;
  147. db.ChangeDatabase(dbConfigId);
  148. db.CodeFirst.InitTables(entityType);
  149. }
  150. // 获取所有实体种子数据
  151. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  152. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  153. if (!seedDataTypes.Any()) return;
  154. foreach (var seedType in seedDataTypes)
  155. {
  156. var instance = Activator.CreateInstance(seedType);
  157. var hasDataMethod = seedType.GetMethod("HasData");
  158. var seedData = ((IList)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  159. if (seedData == null) continue;
  160. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  161. var dbConfigId = entityType.GetCustomAttribute<SqlSugarEntityAttribute>(true).DbConfigId;
  162. db.ChangeDatabase(dbConfigId);
  163. var seedDataTable = seedData.ToList().ToDataTable();
  164. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  165. {
  166. var storage = db.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  167. storage.AsInsertable.ExecuteCommand();
  168. storage.AsUpdateable.ExecuteCommand();
  169. }
  170. else //没有主键或者不是预定义的主键(没主键有重复的可能)
  171. {
  172. var storage = db.Storageable(seedDataTable).ToStorage();
  173. storage.AsInsertable.ExecuteCommand();
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// 配置实体假删除过滤器
  179. /// </summary>
  180. public static void SetDeletedEntityFilter(SqlSugarProvider db)
  181. {
  182. // 获取所有继承基类数据表集合
  183. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  184. && u.BaseType == typeof(EntityBase));
  185. if (!entityTypes.Any()) return;
  186. foreach (var entityType in entityTypes)
  187. {
  188. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  189. db.QueryFilter.Add(new TableFilterItem<object>(entityType, dynamicExpression));
  190. }
  191. }
  192. /// <summary>
  193. /// 配置实体机构过滤器
  194. /// </summary>
  195. public static async void SetOrgEntityFilter(SqlSugarProvider db)
  196. {
  197. // 获取业务数据表集合
  198. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  199. && u.BaseType == typeof(DataEntityBase));
  200. if (!dataEntityTypes.Any()) return;
  201. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  202. if (string.IsNullOrWhiteSpace(userId)) return;
  203. // 获取用户机构Id集合
  204. var orgIds = await App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  205. if (orgIds == null) return;
  206. foreach (var dataEntityType in dataEntityTypes)
  207. {
  208. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  209. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  210. }
  211. }
  212. /// <summary>
  213. /// 配置自定义实体过滤器
  214. /// </summary>
  215. public static void SetCustomEntityFilter(SqlSugarProvider db)
  216. {
  217. // 获取继承自定义实体过滤器接口的类集合
  218. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  219. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  220. if (!entityFilterTypes.Any()) return;
  221. foreach (var entityFilter in entityFilterTypes)
  222. {
  223. var instance = Activator.CreateInstance(entityFilter);
  224. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  225. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  226. if (entityFilters == null) continue;
  227. foreach (TableFilterItem<object> filter in entityFilters)
  228. db.QueryFilter.Add(filter);
  229. }
  230. }
  231. /// <summary>
  232. /// 配置租户实体过滤器
  233. /// </summary>
  234. public static void SetTenantEntityFilter(SqlSugarProvider db)
  235. {
  236. // 获取租户实体数据表集合
  237. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  238. && u.BaseType == typeof(EntityTenant));
  239. if (!dataEntityTypes.Any()) return;
  240. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  241. if (string.IsNullOrWhiteSpace(tenantId)) return;
  242. foreach (var dataEntityType in dataEntityTypes)
  243. {
  244. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  245. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  246. }
  247. }
  248. /// <summary>
  249. /// 处理本地库根目录路径
  250. /// </summary>
  251. /// <param name="dbOptions"></param>
  252. private static void DealConnectionStr(ref ConnectionStringsOptions dbOptions)
  253. {
  254. if (dbOptions.DefaultDbType.Trim().ToLower() == "sqlite" && dbOptions.DefaultConnection.Contains("./"))
  255. {
  256. dbOptions.DefaultConnection = UpdateDbPath(dbOptions.DefaultConnection);
  257. }
  258. dbOptions.DbConfigs.ForEach(cofing =>
  259. {
  260. if (cofing.DbType.Trim().ToLower() == "sqlite" && cofing.DbConnection.Contains("./"))
  261. cofing.DbConnection = UpdateDbPath(cofing.DbConnection);
  262. });
  263. }
  264. private static string UpdateDbPath(string dbConnection)
  265. {
  266. var file = Path.GetFileName(dbConnection.Replace("DataSource=", ""));
  267. return $"DataSource={Environment.CurrentDirectory.Replace(@"\bin\Debug", "")}/{file}";
  268. }
  269. }