SqlSugarRepository.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 大名科技(天津)有限公司版权所有 电话:18020030720 QQ:515096995
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. namespace Admin.NET.Core;
  5. /// <summary>
  6. /// SqlSugar 实体仓储
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
  10. {
  11. protected static ITenant ITenant { get; set; }
  12. protected static SqlSugarScopeProvider MasterDb { get; set; }
  13. public SqlSugarRepository()
  14. {
  15. ITenant ??= App.GetRequiredService<ISqlSugarClient>().AsTenant();
  16. MasterDb ??= ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  17. base.Context = MasterDb;
  18. // 若实体贴有多库特性,则返回指定库连接
  19. if (typeof(T).IsDefined(typeof(TenantAttribute), false))
  20. {
  21. base.Context = ITenant.GetConnectionScopeWithAttr<T>();
  22. return;
  23. }
  24. // 若实体贴有日志表特性,则返回日志库连接
  25. if (typeof(T).IsDefined(typeof(LogTableAttribute), false))
  26. {
  27. base.Context = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
  28. ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
  29. : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  30. return;
  31. }
  32. // 若实体贴有系统表特性,则返回默认库连接
  33. if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
  34. {
  35. base.Context = ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  36. return;
  37. }
  38. // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
  39. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  40. if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
  41. // 根据租户Id切换库连接, 为空则返回默认库连接
  42. var sqlSugarScopeProvider = App.GetRequiredService<SysTenantService>().GetTenantDbConnectionScope(long.Parse(tenantId));
  43. if (sqlSugarScopeProvider == null) return;
  44. base.Context = sqlSugarScopeProvider;
  45. }
  46. }