SqlSugarRepository.cs 2.1 KB

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