SqlsugarSetup.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using SqlSugar;
  4. using gpt_api.Respository;
  5. namespace gpt_api.Web.Core.Setup
  6. {
  7. /// <summary>
  8. /// Sqlsugar 扩展集成
  9. /// </summary>
  10. public static class SqlsugarSetup
  11. {
  12. public static void AddSqlsugarSetup(this IServiceCollection services, string conStr)
  13. {
  14. var configConnection = new ConnectionConfig()
  15. {
  16. DbType = DbType.MySql,
  17. ConnectionString = conStr,
  18. IsAutoCloseConnection = true,
  19. InitKeyType = InitKeyType.Attribute,//从特性读取主键自增信息
  20. };
  21. SqlSugarScope sqlSugar = new SqlSugarScope(configConnection);
  22. sqlSugar.Ado.CommandTimeOut = 10;//单位 秒
  23. sqlSugar.QueryFilter.Add(new SqlFilterItem//单表全局过滤器
  24. {
  25. FilterValue = _filterDb =>
  26. {
  27. return new SqlFilterResult()
  28. {
  29. Sql = " IsDeleted!=1"
  30. };
  31. },
  32. IsJoinQuery = false
  33. })
  34. .Add(new SqlFilterItem//多表全局过滤器
  35. {
  36. FilterValue = _filterDb =>
  37. {
  38. return new SqlFilterResult()
  39. {
  40. Sql = " f.IsDeleted=0"
  41. };
  42. },
  43. IsJoinQuery = true
  44. });
  45. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  46. services.AddScoped(typeof(IRepository<>), typeof(Repository<>));//仓储注册
  47. services.AddUnitOfWork<SqlSugarUnitOfWork>();//启用sqlsugar工作单元(仓储事务)
  48. }
  49. }
  50. }