SqlDataReader.Read() always returning false

六眼飞鱼酱① 提交于 2019-12-24 16:36:55

问题


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!


回答1:


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...



来源:https://stackoverflow.com/questions/1540613/sqldatareader-read-always-returning-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!