SqlSugarSetup.cs 15 KB

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