SqlSugarRepository.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using Furion;
  2. using SqlSugar;
  3. using System.Reflection;
  4. namespace Admin.NET.Core
  5. {
  6. /// <summary>
  7. /// SqlSugar仓储类
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
  11. {
  12. public SqlSugarRepository(ISqlSugarClient context = null) : base(context) // 默认值等于null不能少
  13. {
  14. base.Context = App.GetService<ISqlSugarClient>(); // 切换仓储
  15. // 数据库上下文根据实体切换-业务分库(例如微服务环境)
  16. var entityType = typeof(T);
  17. // 审计日志切换数据库
  18. if (entityType == typeof(SysLogAudit) || entityType == typeof(SysLogEx) || entityType == typeof(SysLogOp) || entityType == typeof(SysLogVis) || entityType == typeof(SysConfig))
  19. {
  20. Context = Context.AsTenant().GetConnectionScope(SqlSugarConst.ConfigId);
  21. }
  22. else
  23. {
  24. // 切换框架数据库
  25. if (entityType.IsDefined(typeof(SqlSugarEntityAttribute), false))
  26. {
  27. var tenantAttribute = entityType.GetCustomAttribute<SqlSugarEntityAttribute>()!;
  28. Context.AsTenant().ChangeDatabase(tenantAttribute.DbConfigId);
  29. }
  30. // 切换租户数据库
  31. if (entityType.IsDefined(typeof(TenantAttribute), false))
  32. {
  33. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>(false)!;
  34. Context.AsTenant().ChangeDatabase(tenantAttribute.configId);
  35. }
  36. }
  37. }
  38. }
  39. }