SqlSugarRepository.cs 1.8 KB

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