The SqlParameter is already contained by another SqlParameterCollection.

Source: Internet
Author: User

The following solutions are available from overseas websites:

Yesterday, I came authentication ss a odd bug while debugging some code for a proof 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 wowould then simply add the parameters to the SqlCommand:

SqlCommand sqlCmd = new SqlCommand (SQL, sqlConn );
SqlCmd. Parameters. AddRange (queryParams );

After executing I wocould close the connection, then code wocould do some other stuff and a different query wocould 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 shocould 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 wocould post. Carry on...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.