So I'm running a query in ADO.NET that I know returns a single row. The relevant portion of my code looks like:
SqlCommand sqc = new SqlCommand();
sqc.Connection = new SqlConnection("connection string");
sqc.CommandText = "SELECT A, B FROM C WHERE D=@d";
sqc.Parameters.AddWithValue("@d", "d");
sqc.Connection.Open();
SqlDataReader rdr = sqc.ExecuteReader();
bool boolio = rdr.Read();
String a = (String)rdr["A"];
When I run this, I get an exception on the final line, complaining that I'm trying to read where there's no data.
When I step through this in VS I inspect rdr before the rdr.Read() line executes and I can see the data I want is sitting in the reader. Then I call rdr.Read() and the result is FALSE, indicating there is no more data for me to read. When I inspect rdr again, the internal ResultsView is empty.
I realize I can get my data simply by discarding the call to Read() BUT: this behaviour is contrary to the MSDN documentation which explicitly says "The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.". It is also contrary to every example of SqlDataReader usage I've found on the web such as this SO question which seems to exist only to taunt me.
Note that I've tested my code against .NET 3.5 and .NET 4.5 with identical results.
Am I missing something? Is there a bug in ADO.NET? Any input is appreciated!
UPDATE 1: The actual exception I get on the last line is:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: Invalid attempt to read when no data is present.
UPDATE 2:
Because Nathan Skerl was unable to reproduce this behavior, and posted verified working code which subsequently failed for me, I suspect there may be an issue with the platforms we're running on. For the record I am using Windows 7 Professional (64-bit) Service Pack 1 and have compiled my project against .NET Framework 3.5 and 4.5 with the same results. If there is any relevant information I have failed to include please let me know and I will add it.