尝试在DataReader中间执行删除时,我一直收到此错误:
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 :(得分: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))
上面的代码可能不完整或正确,但您应该明白这一点。
答案 1 :(得分:0)
尝试将MultipleActiveResultSets = true添加到连接字符串中。