System.InvalidOperationException: 'No row is available' in PostgreSQL

Dung Do Tien Jul 21 2021 218

I have created a small project with .Net Core 3.1 C# and PostgreSQL. I want to get an object of backlink table as below:

using (var db = new PostgresSQL(ConnectionString))
{
    var query = new StringBuilder();
    query.Append("SELECT * ");
    query.Append("FROM public.backlink a WHERE a.id = :_id; ");

    using (var command = db.CreateCommand(query.ToString(), false))
    {
        command.Parameters.Add(new NpgsqlParameter("@_id", id));
        using (var reader = command.ExecuteReader())
        {
            if (reader.HasRows)
            {
                ret.id = (int)reader["id"];
                ret.anchortext = reader["anchortext"] + "";
                ret.titleseo = reader["titleseo"] + "";
            }
        }
    }
}

But when call this method I got an error: System.InvalidOperationException: 'No row is available'

 {System.InvalidOperationException: No row is available
   at Npgsql.NpgsqlDataReader.CheckRow()
   at Npgsql.NpgsqlDataReader.GetValue(Int32 ordinal)

I was debugging but reader.HasRows always true. I don't know why.

How can I fix it?

Have 2 answer(s) found.
  • f

    fahmi zaki Jul 21 2021

    Try adding a reader.Read() call.

     using (var reader = await cmd.ExecuteReaderAsync())
    {
        reader.Read() // <== ADD THIS LINE
        var rowParser = reader.GetRowParser<test>(typeof(test)); 
        result.Add(rowParser(reader)); 
    }

    Good luck!!

  • M

    Minh Vĩnh Jul 21 2021

    You have to call while dr.Read(); to help read a row like this:

     if (reader.HasRows)
    {
        reader.Read();
        ret.id = (int)reader["id"];
        ret.anchortext = reader["anchortext"] + "";
    }

    And it works for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close