When using using() {} (sic) blocks, as shown below, and assuming cmd1 not outside the scope of the first using() {} block, why should the second block throw an exception with a message
SqlParameter is already contained in another SqlParameterCollection
Does this mean that resources and / or descriptors, including parameters ( SqlParameterCollection ) attached to cmd1 , are not freed when it is destroyed at the end of the block?
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); }
NOTE. Doing cmd1.Parameters.Clear () immediately before the last bracket of the first block using () {} will save you from an exception (and possible difficulty).
If you need to reproduce, you can use the following scripts to create objects:
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
John Gathogo Oct 20 '11 at 14:50 2011-10-20 14:50
source share