Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataReader has rows and data, trying to read from it says "no data is present"

I haven't used DataReaders in ages (I prefer to use an ORM) but I'm forced to at work. I pull back the rows, and check that HasRows is true; debugging at this point and examining the reader shows that my data is there.

Now here's the issue: the moment I call reader.Read(), trying to expand the results says "The enumeration yielded no results" or whatever, and I get the "Invalid attempt to read when no data is present." error. I get the same thing if I don't call Read() (which is the default since the DataReader starts before the first record).

I cannot remember the proper way to handle this; the data is there when I check HasRows, but is gone the moment I either try to read from it right after or after I call Read, which makes no sense as if I don't call Read, the reader should still be before the first record, and if the property is set that starts it at the first record (SingleRow? I forget the name of it) is set, then I should be able to read rows without calling Read, however both ways seem to move past the row containing the data.

What am I forgetting? Code is fairly straightforward:

TemplateFile file = null;
using (DbDataReader reader = ExecuteDataReaderProc("GetTemplateByID", idParam)) 
{ 
    if (reader.HasRows) // reader has data at this point - verified with debugger
    { 
        reader.Read(); // loses data at this point if I call Read()
        template = new TemplateFile 
        {
            FileName = Convert.ToString(reader["FileName"]) // whether or not I call
                                                            // Read, says no data here
        };
    }
}
like image 347
Wayne Molina Avatar asked Dec 28 '22 18:12

Wayne Molina


1 Answers

Just to clarify the answer, it was using the debugger since expanding the results view calls Read() and therefore it moves past the row. As Marc Gravell said in a comment: Debugger considered harmful

like image 62
Wayne Molina Avatar answered Jan 18 '23 22:01

Wayne Molina