SqlSugarSetup.cs 15 KB

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