单例模式下出现。。with this Connection which must be closed first. 返回

SqlSugar 老数据
1 2858

创建链接代码:

public static SqlSugarClient GetIntance(int commandTimeOut = 30, DBType dbType = DBType.MySql, bool isAutoCloseConnection = false)
        {
            return SugarBase.InitDB(commandTimeOut, dbType, isAutoCloseConnection);
        }

       
        private static SqlSugarClient InitDB(int commandTimeOut = 30, DBType dbType = DBType.MySql, bool isAutoCloseConnection = false)
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = SugarBase.DBConnectionString,
                DbType = dbType == DBType.SqlServer ? SqlSugar.DbType.SqlServer : SqlSugar.DbType.MySql,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = isAutoCloseConnection
                /*
                 * ,
                 * ,
                SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 },
                     new SlaveConnectionConfig() { HitRate=30, ConnectionString=Config.ConnectionString3 }
                     */
            });
            
            db.Ado.CommandTimeOut = commandTimeOut;
            return db;
        }

我想要的是每个页面只有一个数据库链接,但是多个类里都需要用到,所以每个类我加了个属性

public GroupSub(SqlSugarClient _db)
        {
            db = _db;
        }
        private SqlSugarClient db;






        public void Del(long id)
        {
            db.Deleteable<Group>().In(id).ExecuteCommand();
        }

页面执行如下:

using (var db = SugarBase.GetIntance())
            {

                var ad = new UserSub(db);

                ....省略

                #endregion
                #region 获取分页数据
                Task<Tuple<List<User>, int>> task = ad.ListPageAsync(Convert.ToInt16(pagesize), Convert.ToInt16(page), quesystr, "");
                #region 处理其他数据

                var cd = new GroupSub(db);
                ViewData["group"] = cd.List("");

                #endregion
                var list = await task;
                var listData = list.Item1;
                ViewBag.List = listData;
                。。。。。。。。。。。。。。

                #endregion




            }

问题就出现在

 var cd = new GroupSub(db);
                ViewData["group"] = cd.List("");


提示There is already an open DataReader associated with this Connection which must be closed first.


后来我在using后再using就正常

//using (var db = SugarBase.GetIntance())
            //{
            //    var cd = new GroupSub(db);
            //    ViewData["group"] = cd.List("");
            //}


请问我要怎么改才能在一个页面打开一个数据库链接供所有类使用?

热忱回答1

  • 程序 程序 VIP0
    2018/5/14

    IOC 

    或者 用HttpContext把Db对象缓存到一次的请求会话里

    0 回复