SqlSugarSetup.cs 15 KB

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