title: Why do I get "Invalid attempt to call HasRows when reader is closed" with an open connection?
body: <p>I have this code:</p>
  
  <pre><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></pre>
  
  <p>and this code runs just fine most of the time. Yet sometimes - very rarely - retrieving <code>HasRows</code> yields the following exception:</p>
  
  <pre><code>Invalid attempt to call HasRows when reader is closed.
  System.InvalidOperationException
    at System.Data.SqlClient.SqlDataReader.get_HasRows()
    // my code calling HasRows listed here
  </code></pre>
  
  <p>I'm 99,5% sure the connection is open at that very moment. My code uses <code>HasRows</code> before reading from the reader <a href="http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.80%29.aspx" rel="nofollow">pretty much like MSDN suggests</a>.</p>
  
  <p>What might be the reason for that exception?</p>