DbContext.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using SqlSugar;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace DbHelper
  8. {
  9. public class DbContext
  10. {
  11. private static ConnectionConfig? _config = null;
  12. public static void SetConfig(ConnectionConfig value)
  13. {
  14. _config = value;
  15. }
  16. /// <summary>
  17. /// 用单例模式
  18. /// </summary>
  19. private static readonly SqlSugarScope SqlSugarScope = new SqlSugarScope(new ConnectionConfig()
  20. {
  21. ConnectionString = _config!.ConnectionString, //连接符字串
  22. DbType = _config.DbType, //数据库类型
  23. IsAutoCloseConnection = true //不设成true要手动close
  24. }, db =>
  25. {
  26. //(A)全局生效配置点
  27. //调试SQL事件,可以删掉
  28. db.Aop.OnLogExecuting = (sql, pars) =>
  29. {
  30. DbLog.DBEX(sql);
  31. //输出sql,查看执行sql
  32. //5.0.8.2 获取无参数化 SQL
  33. //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
  34. };
  35. });
  36. /// <summary>
  37. /// 获取db链接
  38. /// </summary>
  39. /// <returns></returns>
  40. /// <exception cref="Exception"></exception>
  41. public static SqlSugarScope Db
  42. {
  43. get
  44. {
  45. if (_config == null) throw new Exception("请使用SetConfig方法写入数据库链接信息");
  46. return SqlSugarScope;
  47. }
  48. }
  49. }
  50. }