SqlSugarSetup.cs 15 KB

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