SqlSugarRepository.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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)) return;
  20. // 若当前未登录或是默认租户Id,则返回默认的连接
  21. var tenantId = App.GetRequiredService<UserManager>().TenantId;
  22. if (tenantId < 1 || tenantId.ToString() == SqlSugarConst.ConfigId) return;
  23. // 根据租户Id切库
  24. if (!iTenant.IsAnyConnection(tenantId.ToString()))
  25. {
  26. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant)
  27. .FirstOrDefault(u => u.Id == tenantId);
  28. iTenant.AddConnection(new ConnectionConfig()
  29. {
  30. ConfigId = tenant.Id,
  31. DbType = tenant.DbType,
  32. ConnectionString = tenant.Connection,
  33. IsAutoCloseConnection = true
  34. });
  35. SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  36. }
  37. base.Context = iTenant.GetConnectionScope(tenantId.ToString());
  38. }
  39. }