Note that there are some explanatory texts on larger screens.

plurals
  1. POThe SqlParameter is already contained by another SqlParameterCollection - Does using() {} cheat?
    primarykey
    data
    text
    <p>While using the <strong>using() {}</strong> (sic) blocks as shown below, and assuming that <strong>cmd1</strong> does not live beyond the scope of the first <strong>using() {}</strong> block, why should the second block throw an exception with the message <strong>The SqlParameter is already contained by another SqlParameterCollection</strong>? Does it mean that resources and/or handles - including the Parameters (SqlParameterCollection) - attached to <strong>cmd1</strong> are not released when its destroyed at the end of the block?</p> <pre><code>using (var conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True")) { var parameters = new SqlParameter[] { new SqlParameter("@ProductId", SqlDbType.Int ) }; using(var cmd1 = new SqlCommand("SELECT ProductName FROM Products WHERE ProductId = @ProductId")) { foreach (var parameter in parameters) { cmd1.Parameters.Add(parameter); } // cmd1.Parameters.Clear(); // uncomment to save your skin! } using (var cmd2 = new SqlCommand("SELECT Review FROM ProductReviews WHERE ProductId = @ProductId")) { foreach (var parameter in parameters) { cmd2.Parameters.Add(parameter); } } } </code></pre> <p><strong>NOTE:</strong> Doing cmd1.Parameters.Clear() just before the last brace of the first <strong>using() {}</strong> block will save you from the exception (and possible embarrassment).</p> <p>If you need to reproduce you can use the following scripts to create the objects:</p> <pre><code>CREATE TABLE Products( ProductId int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED, ProductName nvarchar(32) NOT NULL) GO CREATE TABLE ProductReviews( ReviewId int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED, ProductId int NOT NULL, Review nvarchar(128) NOT NULL) GO </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload