SqlSugarRepository.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // 连接配置
  36. var connectionConfig = new DbConnectionConfig
  37. {
  38. ConfigId = tenant.Id,
  39. DbType = tenant.DbType,
  40. IsAutoCloseConnection = true,
  41. };
  42. if (tenant.TenantType == TenantTypeEnum.Id)
  43. {
  44. // 如果是Id隔离,使用默认的连接字符串
  45. connectionConfig.ConnectionString = iTenant.GetConnectionScope(SqlSugarConst.ConfigId).CurrentConnectionConfig.ConnectionString;
  46. // 继承主库的“启用驼峰转下划线”设置
  47. connectionConfig.EnableUnderLine = mainConnConfig.EnableUnderLine;
  48. }
  49. else
  50. {
  51. connectionConfig.ConnectionString = tenant.Connection;
  52. }
  53. iTenant.AddConnection(connectionConfig);
  54. SqlSugarSetup.SetDbConfig(connectionConfig);
  55. SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  56. }
  57. base.Context = iTenant.GetConnectionScope(tenantId.ToString());
  58. }
  59. }