DbContext.cs 1.5 KB

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