The SqlParameter is already contained by another SqlParameterCollection.
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...






Blogger comments
Thanks a ton.
Thanks much for this post: it's been helpful!
Please do this as you run into future problems / oddities !
/JoLu
Is there any other way to play around this.... thanks