SqlSugarRepository.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. base.Context = iTenant.IsAnyConnection(SqlSugarConst.LogConfigId)
  24. ? iTenant.GetConnectionScope(SqlSugarConst.LogConfigId)
  25. : iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  26. return;
  27. }
  28. // 若实体贴有系统表特性,则返回默认库连接
  29. if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
  30. {
  31. base.Context = iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  32. return;
  33. }
  34. // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
  35. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  36. if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
  37. // 根据租户Id切换库连接, 为空则返回默认库连接
  38. var sqlSugarScopeProvider = App.GetRequiredService<SysTenantService>().GetTenantDbConnectionScope(long.Parse(tenantId));
  39. if (sqlSugarScopeProvider == null) return;
  40. base.Context = sqlSugarScopeProvider;
  41. }
  42. }