System.IndexOutOfRangeException SQLDataReader

0
Hello, I'm trying to make a code read what you have in the SQL Server DataBase, but I'm getting this error:

System.IndexOutOfRangeException: Pontos
   em  System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
   em  System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
   em  System.Data.SqlClient.SqlDataReader.get_Item(String name)

Code:

public Usuario InitUsuario(SqlDataReader reader)
{
    Usuario usuario = new Usuario();
    usuario.pontos = (int)reader["Pontos"];
    return usuario;
}
    
asked by anonymous 18.09.2017 / 15:57

1 answer

3

First point, as it is a DataReader, you have to iterate over it to be able to read some value, even if the query returns only one line. Change your code to the following:

public Usuario InitUsuario(SqlDataReader reader)
{
    if(reader.HasRows)
    {
        while(reader.Read())
        {
            Usuario usuario = new Usuario();
            usuario.pontos = (int)reader["Pontos"];
            return usuario;
        }
    }

    reader.Close();
}

I do not know what situation you're going to use reader in, but if that's the case, as it's only a user you're probably reading, it's better to use a DataAdapter, or to get accustomed to MicroORM's, like Dapper. >     

25.09.2017 / 13:30