2010-07-28 37 views
1

當試圖在我的DataReader中間執行刪除我不斷收到此錯誤:CLR信息:System.InvalidOperationException:上下文連接已在使用

System.InvalidOperationException:上下文連接已在使用。

我得到所有需要刪除的行,然後遍歷數據讀取器,因爲返回的行很多。

SqlConnection conn = new SqlConnection(「context connection = true」);

 SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = conn; 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.CommandText = "spClean_Select_Product_For_Delete"; 
     cmd.CommandTimeout = 41600; 

     conn.Open(); 
     SqlDataReader reader = cmd.ExecuteReader(); 

     try 
     { 
      SqlContext.Pipe.Send(DateTime.Now.ToString() + " - Started working with Product"); 

      while (reader.Read()) 
      { 
       SqlContext.Pipe.ExecuteAndSend(new SqlCommand("DELETE FROM ProductInfo WHERE ProductId = " 
        + reader["ProductId"].ToString())); 
      } 

      SqlContext.Pipe.Send(DateTime.Now.ToString() + " - Completed working with Product"); 
     } 
     finally 
     { 
      conn.Close(); 
      // Always call Close when done reading. 
      reader.Close(); 
     } 
+0

如果以下任何答案是正確的,您能否將其標記爲已回答? – 2011-04-26 05:57:51

回答

2

此例外情況的最可能原因是您在選擇要刪除的記錄的同時將刪除命令發送到服務器。我建議你先收集要刪除才把所有產品ID刪除:

ICollection<int> productIds = new HashSet<int>(); 
using (var cmd = new SqlCommand("spClean_Select_Product_For_Delete")) 
{ 
    using (var reader = cmd.ExecuteReader()) 
    { 
     var productId = (int) reader["ProductId"]; 
     productIds.Add(productId); 
    } 
} 
string deleteCmdString = 
    "DELETE FROM Product WHERE ProductId IN (" + productIdsString + ")"; 
SqlContext.Pipe.ExecuteAndSend(new SqlCommand(deleteCmdString)) 

上面的代碼可能是不完整或不正確的,但你應該明白我的意思。

0

嘗試爲連接字符串添加MultipleActiveResultSets = true。

相關問題