2

I have the following situation:

using (SqlConnection conexao = new SqlConnection(ConnectionString))
{
 SqlCommand comando = new SqlCommand(query, conexao);
 comando.Parameters.AddWithValue("id", idUsuario);
 conexao.Open();
 SqlDataReader reader = comando.ExecuteReader(CommandBehavior.SingleRow);
 if (reader.Read())
 {
 Hydrate(out entity, reader);
 }
}

So, if reader contains valid results and HasRows == true, then reader.Read() should return true, right?

Well, it doesn't for me. I have no idea of what is going on, because the Hydrate(out entity, reader); line is never getting hit.

Can someone please help me understand this?

Thank you!

skaffman
404k96 gold badges824 silver badges775 bronze badges
asked Oct 8, 2009 at 21:29

1 Answer 1

11

Actually, what happens is SqlDataReader.Read returns true if it is NOT the last row.

Your behavior specifies "SingleRow", so the reader aligns the reader to the first row, and returns false saying "there are no rows left after this one".

See this link Here for the documentation on this: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx

"true if there are more rows; otherwise false."

Of interest, however, their examples seem like they would ignore the very last row based on that sentence...

answered Oct 8, 2009 at 21:31
1
  • I know this is old, but in case anyone else reads this, I feel this could be misleading. Microsoft's documentation (in the Remarks) says The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data. I take this to mean calling Read returns true when there is a row to read (the row pointer is at a valid row). If you are on the last row and call Read it will return false because there is nothing after, but if you are on the second last and call Read, it will return True and move the row pointer to the last row. Commented Mar 11, 2023 at 0:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.