SqlSugarSetup.cs 15 KB

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