SqlSugarRepository.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. // 根据当前租户Id切换数据库
  13. var tenantId = App.GetRequiredService<UserManager>().TenantId;
  14. if (tenantId > 1)
  15. {
  16. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
  17. if (!iTenant.IsAnyConnection(tenant.ConfigId))
  18. {
  19. iTenant.AddConnection(new ConnectionConfig()
  20. {
  21. ConfigId = tenant.ConfigId,
  22. ConnectionString = tenant.Connection,
  23. DbType = tenant.DbType,
  24. IsAutoCloseConnection = true
  25. });
  26. }
  27. base.Context = iTenant.GetConnectionScope(tenant.ConfigId);
  28. }
  29. else
  30. {
  31. base.Context = iTenant.GetConnectionScopeWithAttr<T>();
  32. }
  33. }
  34. }