SqlSugarRepository.cs 1.8 KB

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