I have this 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
}
}
}
}
and this code runs just fine most of the time. Yet sometimes – very rarely – retrieving HasRows yields the following exception:
Invalid attempt to call HasRows when reader is closed.
System.InvalidOperationException
at System.Data.SqlClient.SqlDataReader.get_HasRows()
// my code calling HasRows listed here
I’m 99,5% sure the connection is open at that very moment. My code uses HasRows before reading from the reader pretty much like MSDN suggests.
What might be the reason for that exception?
This happens to be unexpected behavior in
ExecuteReader()– most likely a bug. Deep insideExecuteReader()some random error occurs, most likely a network timeout, the connection is closed and then a closedSqlDataReaderis returned as if nothing happened. No wonder subsequent call toHasRowsyields an exception.