Mr. Boy Mr. Boy - 1 year ago 108
SQL Question

DBReader has rows but Read() returns false

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

In the debugger I can see my reader has one row - I can see the data returned - but
is returning
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?

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download