本文介绍了为什么我得到"无效试图调用HasRows当阅读器被关闭"以开放的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个code:
// 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
}
}
}
}
这code运行得很好的大部分时间。然而,有时 - 很少 - 检索 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%,确保连接在那一刻开启。我的code使用 HasRows
从阅读器的。
这可能是该异常的原因是什么?
What might be the reason for that exception?
推荐答案
这恰好是意外的行为在的ExecuteReader()
- 很可能是一个错误。内心深处的ExecuteReader()
一些随机的错误发生时,最有可能是网络超时,关闭连接,然后封闭 SqlDataReader的
返回,就好像什么都没有发生。难怪后续调用 HasRows
产生一个例外。
This happens to be unexpected behavior in ExecuteReader()
- most likely a bug. Deep inside ExecuteReader()
some random error occurs, most likely a network timeout, the connection is closed and then a closed SqlDataReader
is returned as if nothing happened. No wonder subsequent call to HasRows
yields an exception.
这篇关于为什么我得到"无效试图调用HasRows当阅读器被关闭"以开放的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!