The SqlParameter is already contained by another SqlParameterCollection.

在调试一个概念验证应用时,遇到使用同一组SQL参数执行不同SqlCommand对象导致的SqlParameter已由另一个SqlParameterCollection包含异常。通过在执行后清理SqlCommand参数解决了此问题。

以下是从国外网站找到的 解决办法

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...

转载于:https://www.cnblogs.com/ywqu/archive/2009/02/22/1396004.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值