DbContext.cs 1.4 KB

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