SqlSugarRepository.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. namespace Admin.NET.Core;
  2. /// <summary>
  3. /// SqlSugar仓储类
  4. /// </summary>
  5. /// <typeparam name="T"></typeparam>
  6. public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
  7. {
  8. protected ITenant iTenant = null; // 多租户事务
  9. public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
  10. {
  11. iTenant = App.GetRequiredService<ISqlSugarClient>().AsTenant();
  12. // 若实体贴有多库特性,则返回指定的连接
  13. if (typeof(T).IsDefined(typeof(TenantAttribute), false))
  14. {
  15. base.Context = iTenant.GetConnectionScopeWithAttr<T>();
  16. return;
  17. }
  18. // 若实体贴有系统表特性,则返回默认的连接
  19. if (typeof(T).IsDefined(typeof(SystemTableAttribute), false))
  20. {
  21. base.Context = iTenant.GetConnectionScope(SqlSugarConst.ConfigId);
  22. return;
  23. }
  24. // 若当前未登录或是默认租户Id,则返回默认的连接
  25. var tenantId = App.GetRequiredService<UserManager>().TenantId;
  26. if (tenantId < 1 || tenantId.ToString() == SqlSugarConst.ConfigId) return;
  27. // 根据租户Id切库
  28. if (!iTenant.IsAnyConnection(tenantId.ToString()))
  29. {
  30. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant)
  31. .FirstOrDefault(u => u.Id == tenantId);
  32. // 如果是Id隔离,使用默认的连接字符串
  33. var connectionString = tenant.TenantType == TenantTypeEnum.Id ? iTenant.GetConnectionScope(SqlSugarConst.ConfigId).CurrentConnectionConfig.ConnectionString : tenant.Connection;
  34. iTenant.AddConnection(new ConnectionConfig()
  35. {
  36. ConfigId = tenant.Id,
  37. DbType = tenant.DbType,
  38. ConnectionString = connectionString,
  39. IsAutoCloseConnection = true
  40. });
  41. SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  42. }
  43. base.Context = iTenant.GetConnectionScope(tenantId.ToString());
  44. }
  45. }