我的代码如下:
protected SqlDataReader ExecuteReader(string cmdText, CommandType cmdType)
        {
            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(cmdText, cn);
                cmd.CommandType = cmdType;
                cn.Open();
                return cmd.ExecuteReader( CommandBehavior.CloseConnection);
            }
        } public List<Category> getShopCategoryList()
        {
            string command = "dbo.GetCategoryList";
            List<ShopCategoryDetails> list = new List<Category>();
            SqlDataReader reader = ExecuteReader(command, CommandType.StoredProcedure);
            
            while (reader.Read())
            {
                list.Add(new ShopCategoryDetails((int)reader[0],reader[1].ToString()));
            }
            return list;
        }在读到while (reader.Read())这句时,就给报错:阅读器关闭时尝试调用 Read 无效。 异常详细信息: System.InvalidOperationException: 阅读器关闭时尝试调用 Read 无效。请问这咋整啊

解决方案 »

  1.   

    ExecuteReader执行之后,SqlConnection 会被立刻dispose,你的reader 接下来就不能访问了。解决办法,要不不用reader ,用dataset,要不就不要释放SqlConnection 
      

  2.   

       using (SqlConnection cn = new SqlConnection(ConnectionString)) 
                { 
                    SqlCommand cmd = new SqlCommand(cmdText, cn); 
                    cmd.CommandType = cmdType; 
                    cn.Open(); 
                    return cmd.ExecuteReader( CommandBehavior.CloseConnection); 
                } //在这里connection就已经close了,因为你使用了use你可以试着讲SqlConnection cn 变成类成员变量。但是要记得close它。
      

  3.   

    你把SqlConnection放在using中,当using(){}执行完毕后,cn对象会释放,所以无效,
    不要使用using应该可以