在使用如下所示的using() {}
(sic)块时,假设cmd1
不超出第一个using() {}
块的范围,为什么第二个块会抛出消息
SqlParameter已包含在另一个SqlParameterCollection
中
是否意味着资源和/或句柄 - 包括附加到SqlParameterCollection
的参数(cmd1
) - 在块的末尾被销毁时不会被释放?
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);
}
}
}
注意:在第一个 using(){} 块的最后一个大括号之前执行cmd1.Parameters.Clear()将使您免于异常(并且可能尴尬)。
如果需要重现,可以使用以下脚本创建对象:
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
答案 0 :(得分:87)
我怀疑SqlParameter
“知道”它是哪一个命令,并且在处理命令时不会清除该信息,但是当你调用{{1}时 被清除}}
我个人认为我首先要避免重复使用这些物品,但这取决于你:)
答案 1 :(得分:8)
使用块不能确保对象被“销毁”,只需调用Dispose()
方法即可。实际做的是取决于具体的实现,在这种情况下,它显然不会清空集合。我们的想法是确保垃圾收集器无法清理的非托管资源得到正确处理。由于Parameters集合不是非托管资源,因此它不会完全令人惊讶,它不会被dispose方法清除。
答案 2 :(得分:4)
添加cmd.Parameters.Clear();执行后应该没问题。
答案 3 :(得分:3)
using
定义范围,自动调用我们喜欢的Dispose()
。
超出范围的引用不会使对象本身“消失”,如果另一个对象有引用它,在这种情况下,parameters
引用cmd1
的情况就是这种情况
答案 4 :(得分:2)
基于我举的例子,我也遇到了同样的问题,谢谢@Jon。
当我调用下面的函数时,两次传递相同的sqlparameter。在第一次数据库调用中,它被正确调用,但是在第二次数据库调用中,出现了上述错误。
public Claim GetClaim(long ClaimId)
{
string command = "SELECT * FROM tblClaim "
+ " WHERE RecordStatus = 1 and ClaimId = @ClaimId and ClientId =@ClientId";
List<SqlParameter> objLSP_Proc = new List<SqlParameter>(){
new SqlParameter("@ClientId", SessionModel.ClientId),
new SqlParameter("@ClaimId", ClaimId)
};
DataTable dt = GetDataTable(command, objLSP_Proc);
if (dt.Rows.Count == 0)
{
return null;
}
List<Claim> list = TableToList(dt);
command = "SELECT * FROM tblClaimAttachment WHERE RecordStatus = 1 and ClaimId = @ClaimId and ClientId =@ClientId";
DataTable dt = GetDataTable(command, objLSP_Proc); //gives error here, after add `sqlComm.Parameters.Clear();` in GetDataTable (below) function, the error resolved.
retClaim.Attachments = new ClaimAttachs().SelectMany(command, objLSP_Proc);
return retClaim;
}
这是常见的DAL功能
public DataTable GetDataTable(string strSql, List<SqlParameter> parameters)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection connection = this.GetConnection())
{
SqlCommand sqlComm = new SqlCommand(strSql, connection);
if (parameters != null && parameters.Count > 0)
{
sqlComm.Parameters.AddRange(parameters.ToArray());
}
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = sqlComm;
da.Fill(dt);
}
sqlComm.Parameters.Clear(); //this added and error resolved
}
}
catch (Exception ex)
{
throw;
}
return dt;
}
答案 5 :(得分:1)
我遇到了这个特殊错误,因为我使用相同的SqlParameter对象作为SqlParameter集合的一部分来多次调用过程。发生此错误恕我直言的原因是SqlParameter对象与特定的SqlParameter集合相关联,并且您不能使用相同的SqlParameter对象来创建新的SqlParameter集合。
所以,而不是-
var param1 =新的SqlParameter {DbType = DbType.String,ParameterName = param1,Direction = ParameterDirection.Input,值=“”};
var param2 = new SqlParameter {DbType = DbType.Int64,ParameterName = param2,Direction = ParameterDirection.Input,Value = 100};
SqlParameter [] sqlParameter1 = new [] {param1,param2};
ExecuteProc(sp_name,sqlParameter1);
/ *错误:
SqlParameter [] sqlParameter2 = new [] {param1,param2};
ExecuteProc(sp_name,sqlParameter2);
* /
执行此操作-
var param3 =新的SqlParameter {DbType = DbType.String,ParameterName = param1,Direction = ParameterDirection.Input,Value = param1.Value};
var param4 =新的SqlParameter {DbType = DbType.Int64,ParameterName = param2,Direction = ParameterDirection.Input,Value = param2.Value};
SqlParameter [] sqlParameter3 = new [] {param3,param4}; ExecuteProc(sp_name,sqlParameter3);
答案 6 :(得分:0)
我遇到了这个异常,因为我无法实例化参数对象。我以为它抱怨两个程序具有相同名称的参数。它抱怨两次添加相同的参数。
Dim aParm As New SqlParameter()
aParm.ParameterName = "NAR_ID" : aParm.Value = hfCurrentNAR_ID.Value
m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)
aParm = New SqlParameter
Dim tbxDriveFile As TextBox = gvNetworkFileAccess.Rows(index).FindControl("tbxDriveFolderFile")
aParm.ParameterName = "DriveFolderFile" : aParm.Value = tbxDriveFile.Text
m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)
**aParm = New SqlParameter()** <--This line was missing.
Dim aDDL As DropDownList = gvNetworkFileAccess.Rows(index).FindControl("ddlFileAccess")
aParm.ParameterName = "AccessGranted" : aParm.Value = aDDL.Text
**m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)** <-- The error occurred here.
答案 7 :(得分:0)
问题
遇到此问题时,我正在从C#执行SQL Server存储过程:
异常消息[该SqlParameter已被另一个SqlParameterCollection包含。]
原因
我将3个参数传递给存储过程。我添加了
param = command.CreateParameter();
总共只有一次。我应该为每个参数添加此行,这意味着总共3次。
DbCommand command = CreateCommand(ct.SourceServer, ct.SourceInstance, ct.SourceDatabase);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "[ETL].[pGenerateScriptToCreateIndex]";
DbParameter param = command.CreateParameter();
param.ParameterName = "@IndexTypeID";
param.DbType = DbType.Int16;
param.Value = 1;
command.Parameters.Add(param);
param = command.CreateParameter(); --This is the line I was missing
param.ParameterName = "@SchemaName";
param.DbType = DbType.String;
param.Value = ct.SourceSchema;
command.Parameters.Add(param);
param = command.CreateParameter(); --This is the line I was missing
param.ParameterName = "@TableName";
param.DbType = DbType.String;
param.Value = ct.SourceDataObjectName;
command.Parameters.Add(param);
dt = ExecuteSelectCommand(command);
解决方案
为每个参数添加以下代码行
param = command.CreateParameter();
答案 8 :(得分:0)
这就是我的方法!
ILease lease = (ILease)_SqlParameterCollection.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(5);
lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
lease.RenewOnCallTime = TimeSpan.FromMinutes(2);
lease.Renew(new TimeSpan(0, 5, 0));
}
答案 9 :(得分:0)
我也有同样的例外。就我而言,我是通过EntityFramework DBContext调用SQL的。以下是我的代码以及如何修复它。
string sql = "UserReport @userID, @startDate, @endDate";
var sqlParams = new Object[]
{
new SqlParameter { ParameterName= "@userID", Value = p.UserID, SqlDbType = SqlDbType.Int, IsNullable = true }
,new SqlParameter { ParameterName= "@startDate", Value = p.StartDate, SqlDbType = SqlDbType.DateTime, IsNullable = true }
,new SqlParameter { ParameterName= "@endDate", Value = p.EndDate, SqlDbType = SqlDbType.DateTime, IsNullable = true }
};
IEnumerable<T> rows = ctx.Database.SqlQuery<T>(sql,parameters);
foreach(var row in rows) {
// do something
}
// the following call to .Count() is what triggers the exception
if (rows.Count() == 0) {
// tell user there are no rows
}
注意:上面对SqlQuery<T>()
的调用实际上返回了一个DbRawSqlQuery<T>
,它实现了IEnumerable
我还没有启动SQL Profiler进行确认,但是我怀疑.Count()
触发了对SQL Server的另一个调用,并且在内部它正在重用相同的SQLCommand
对象并尝试重新添加重复的参数。
我在foreach
内添加了一个计数器,这样我就可以保持行数而不必调用.Count()
int rowCount = 0;
foreach(var row in rows) {
rowCount++
// do something
}
if (rowCount == 0) {
// tell user there are no rows
}
我的项目可能正在使用EF的旧版本。较新的版本可能通过清除参数或处置SqlCommand
对象而解决了此内部错误。
或者,也许有明确的指令告诉开发人员在迭代.Count()
之后不要调用DbRawSqlQuery
,而我将其编码错误。