我有这样的代码:为什么打开连接时会出现“无法尝试在阅读器关闭时调用HasRows”?
// this is managed elsewhere
SqlConnection connection =...
connection.Open();
// this is one block of code, separate from the above
using(var transaction = connection.BeginTransaction()) {
using(var command = connection.CreateCommand()) {
command.Transaction = transaction;
command.CommandText = ...
using(var reader = command.ExecuteReader()) {
if(reader.HasRows) {
if(reader.Read()) {
//get data from the reader
}
}
}
}
,并运行此代码就好了大部分的时间。然而,有时 - 很少 - 检索HasRows
产生以下异常:
Invalid attempt to call HasRows when reader is closed.
System.InvalidOperationException
at System.Data.SqlClient.SqlDataReader.get_HasRows()
// my code calling HasRows listed here
我99.5%,确保连接在那一刻开启。在从读者pretty much like MSDN suggests读取之前,我的代码使用HasRows
。
什么可能是该例外的原因?
它是什么类型的应用程序(f.e。ASP.NET),其中是初始化和声明的连接,是静态的,启用了“Connection-Pooling”,你为什么重用它?我会在使用它的'using-statement'中创建它。 –
你在那时检查了连接的状态是什么? http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx –
@astander:不,否则我不会说我99.5%肯定。 – sharptooth