Search code examples
c#sql.netsql-serverdbconnection

DBReader has rows but Read() returns false


using (var conn = new SqlConnection(connectionString))
{
    var cmd = new SqlCommand("SELECT * FROM mySchema.MyTable", conn);
    conn.Open();
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {...

In the debugger I can see my reader has one row - I can see the data returned - but reader.Read is returning false so my processing code is not getting called.

This seems pretty basic "read rows from a database table" stuff so what am I missing? Should I be looking at the reader's row data directly or something?


Solution

  • If you let the debugger show you the results, it will read out the reader and enumerate the result.

    See the comment in the debugger window:

    Results View: Expanding the Results View will enumerate the IEnumerable

    So your debugger already read out all results and if you step to reader.Read() there are no more rows to read and Read() returns false.


    I just reproduced it with a litte test. When my debugger reads the results, my code can't read them anymore. If I don't let the debugger show them, my code can read them. (qed)