以下是從國外網站找到的 解決辦法
Yesterday, I came across a odd bug while debugging some code for a proof of concept application.
The code itself was simple connecting to the database, executing two queries using different SqlCommand objects, but the same SqlParameter collection and returning the results to the user.
The method itself look two parameters, a SQL query as a string and a SQL Parameter[]. I would then simply add the parameters to the SqlCommand:
SqlCommand sqlCmd = new SqlCommand(sql, sqlConn);
sqlCmd.Parameters.AddRange(queryParams);
After executing I would close the connection, then code would do some other stuff and a different query would be executed but using the same parameter collection. In theory, there is no reason why this wouldn't work however the code was throwing an exception with the error "The SqlParameter is already contained by another SqlParameterCollection." How odd, I had closed the connection and it shouldn't be referred so I should be able to add it.
Turns out, or at least I think, that the garage collection isn't kicking in quick enough and so the reference is still alive. Quick fix was to clear the parameters on the SqlCommand object after execution.
sqlCmd.Parameters.Clear();
Tripped me up for a little bit so I thought I would post. Carry on...
版權
作者:靈動生活 郝憲玮
如果你認為此文章有用,請點選底端的【推薦】讓其他人也了解此文章,

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。