SqlSugarRepository.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // 获取主库连接配置
  33. var dbOptions = App.GetOptions<DbConnectionOptions>();
  34. var mainConnConfig = dbOptions.ConnectionConfigs.First(u => u.ConfigId == SqlSugarConst.ConfigId);
  35. // 如果是Id隔离,使用默认的连接字符串
  36. var connectionString = tenant.TenantType == TenantTypeEnum.Id ? iTenant.GetConnectionScope(SqlSugarConst.ConfigId).CurrentConnectionConfig.ConnectionString : tenant.Connection;
  37. var connectionConfig = new DbConnectionConfig
  38. {
  39. ConfigId = tenant.Id,
  40. DbType = tenant.DbType,
  41. ConnectionString = connectionString,
  42. IsAutoCloseConnection = true,
  43. // 继承主库的“启用驼峰转下划线”设置
  44. EnableUnderLine = mainConnConfig.EnableUnderLine,
  45. };
  46. iTenant.AddConnection(connectionConfig);
  47. SqlSugarSetup.SetDbConfig(connectionConfig);
  48. SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  49. }
  50. base.Context = iTenant.GetConnectionScope(tenantId.ToString());
  51. }
  52. }