Home Ask Login Register

Developers Planet

Your answer is one click away!

Subpar Web Dev February 2016

Why am I getting 'Invalid attempt to read when no data is present' here?

My stored procedure is the simple one-liner

CREATE PROCEDURE CheckIfFinished    
    @pid UNIQUEIDENTIFIER 
AS  
BEGIN
    SELECT finished 
    FROM Partners 
    WHERE id = @pid   
END  

and I'm calling it from my C# code like

using (SqlCommand cmd = new SqlCommand("CheckIfFinished", this._Conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@pid", pid);

    this._Conn.Open();

    using (SqlDataReader dataReader = cmd.ExecuteReader())
    {
        finished = dataReader.GetByte(0) == 1 ? true : false;
    }

    this._Conn.Close();
}

The column finished in the Partners table is of type TINYINT NOT NULL DEFAULT 0

Stack trace of error is

[InvalidOperationException: Invalid attempt to read when no data is present.]
System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName) +6531242
System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) +81
System.Data.SqlClient.SqlDataReader.ReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) +25
System.Data.SqlClient.SqlDataReader.GetByte(Int32 i) +27
Survey.Models.SurveyDbModel.CheckIfFinished(Guid pid) +230

Where am I going wrong here?

Answers


Gusman February 2016

You forgot dataReader.Read().

Until you don't execute Read() on a data reader, the data is not available.

Post Status

Asked in February 2016
Viewed 2,514 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life