I have some C# code that dynamically generates an SQL query and executes it via IDbCommand.ExecuteScalar(). This works fine; there’s exactly one result that matches my query in the DB, and that result is always returned.
But just recently, as the first step in a refactoring to support multiple matches in the DB, I replaced the call to ExecuteScalar() with one to ExecuteReader(). Everything else in the setup and DB access is the same. But the returned IDataReader contains no data, and throws InvalidOperationExceptions whenever I try to get data out of it.
I know the data’s still there; everything works fine when I switch back to ExecuteScalar(). How is this possible?
Make sure that you are calling the Read() method on the IDataReader that is returned by
ExecuteReader()before trying to access it. CallingRead()will advance the reader onto the first (and in your case only) row of the resultset. If you do not callRead()before accessing theIDataReader, you will get anInvalidOperationExceptionwhen you try to access its data – as you are experiencing.