SqlSugarRepository.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  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.IsDefined(typeof(SqlSugarEntityAttribute), false))
  19. {
  20. var tenantAttribute = entityType.GetCustomAttribute<SqlSugarEntityAttribute>()!;
  21. Context.AsTenant().ChangeDatabase(tenantAttribute.DbConfigId);
  22. }
  23. // 切换租户数据库
  24. if (entityType.IsDefined(typeof(TenantAttribute), false))
  25. {
  26. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>(false)!;
  27. Context.AsTenant().ChangeDatabase(tenantAttribute.configId);
  28. }
  29. }
  30. }
  31. }