SqlSugarRepository.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Furion;
  2. using SqlSugar;
  3. using System.Reflection;
  4. namespace Admin.NET.Core
  5. {
  6. /// <summary>
  7. /// SqlSugar仓储类
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
  11. {
  12. public SqlSugarRepository(ISqlSugarClient context = null) : base(context) // 默认值等于null不能少
  13. {
  14. base.Context = App.GetService<ISqlSugarClient>(); // 用手动获取方式支持切换仓储
  15. // 数据库上下文根据实体切换,业务分库(使用环境例如微服务)
  16. var entityType = typeof(T);
  17. //审计日志,获取系统配置需要切库
  18. if (entityType == typeof(SysLogAudit) || entityType == typeof(SysLogEx) || entityType == typeof(SysLogOp) || entityType == typeof(SysLogVis) || entityType == typeof(SysConfig))
  19. {
  20. Context = Context.AsTenant().GetConnectionScope(SqlSugarConst.ConfigId);
  21. }
  22. else
  23. {
  24. // 切换框架数据库
  25. if (entityType.IsDefined(typeof(SqlSugarEntityAttribute), false))
  26. {
  27. var tenantAttribute = entityType.GetCustomAttribute<SqlSugarEntityAttribute>()!;
  28. Context.AsTenant().ChangeDatabase(tenantAttribute.DbConfigId);
  29. }
  30. // 切换租户数据库
  31. if (entityType.IsDefined(typeof(TenantAttribute), false))
  32. {
  33. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>(false)!;
  34. Context.AsTenant().ChangeDatabase(tenantAttribute.configId);
  35. }
  36. }
  37. }
  38. }
  39. }