SqlSugarRepository.cs 1.4 KB

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