SqlSugarRepository.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. public SqlSugarRepository(ITenant iTenant)
  12. {
  13. base.Context = iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  14. // 若实体贴有多库特性,则返回指定库连接
  15. if (typeof(T).IsDefined(typeof(TenantAttribute), false))
  16. {
  17. base.Context = iTenant.GetConnectionScopeWithAttr<T>();
  18. return;
  19. }
  20. // 若实体贴有日志表特性,则返回日志库连接
  21. if (typeof(T).IsDefined(typeof(LogTableAttribute), false))
  22. {
  23. if (iTenant.IsAnyConnection(SqlSugarConst.LogConfigId))
  24. base.Context = iTenant.GetConnectionScope(SqlSugarConst.LogConfigId);
  25. return;
  26. }
  27. // 若实体贴有系统表特性,则返回默认库连接
  28. if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
  29. return;
  30. // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
  31. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  32. if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
  33. // 根据租户Id切换库连接, 为空则返回默认库连接
  34. var sqlSugarScopeProviderTenant = App.GetRequiredService<SysTenantService>().GetTenantDbConnectionScope(long.Parse(tenantId));
  35. if (sqlSugarScopeProviderTenant == null) return;
  36. base.Context = sqlSugarScopeProviderTenant;
  37. }
  38. }