SqlSugarRepository.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. public SqlSugarRepository(ISqlSugarClient context = null) : base(context) // 默认值等于null不能少
  9. {
  10. base.Context = App.GetService<ISqlSugarClient>(); // 切换仓储
  11. // 数据库上下文根据实体切换-业务分库(例如微服务环境)
  12. var entityType = typeof(T);
  13. // 审计日志切换数据库
  14. if (entityType == typeof(SysLogAudit) || entityType == typeof(SysLogEx) || entityType == typeof(SysLogOp) || entityType == typeof(SysLogVis) || entityType == typeof(SysConfig))
  15. {
  16. Context = Context.AsTenant().GetConnectionScope(SqlSugarConst.ConfigId);
  17. }
  18. else
  19. {
  20. // 切换框架数据库
  21. if (entityType.IsDefined(typeof(SqlSugarEntityAttribute), false))
  22. {
  23. var tenantAttribute = entityType.GetCustomAttribute<SqlSugarEntityAttribute>()!;
  24. Context.AsTenant().ChangeDatabase(tenantAttribute.DbConfigId);
  25. }
  26. // 切换租户数据库
  27. if (entityType.IsDefined(typeof(TenantAttribute), false))
  28. {
  29. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>(false)!;
  30. Context.AsTenant().ChangeDatabase(tenantAttribute.configId);
  31. }
  32. }
  33. }
  34. }