The DataReader has rows and data, trying to read from it, it says: "no data",

I have not used DataReaders in ages (I prefer to use ORM), but I have to work. I unlock the lines and verify that HasRows true; debugging at this stage and examining the reader shows that my data is there.

Now here is the problem: the moment I call reader.Read() , trying to expand the results, it says: “Enumeration did not produce any results” or something else, and I get “Invalid attempt to read when there is no data”. error. I get the same if I do not call Read() (this is the default value since the DataReader runs before the first write).

I cannot remember the right way to handle this; the data is there when I check HasRows , but left at the moment when I either try to read it right after or after I call Read , which does not make sense, as if I did not call Read , the reader should still be up to of the first record, and if a property is set that starts it in the first record (SingleRow? Have I forgotten its name), then I should be able to read lines without calling Read, however both paths seem to be moved beyond the line containing the data.

What am I forgetting? The code is pretty simple:

 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 }; } } 
+4
source share
2 answers

To clarify the answer, he used a debugger, since the extension of the presentation of the results calls Read() , and therefore it moves over the line. As Mark Gravell said in a comment: The debugger is considered harmful

+9
source

If you want to put data in a file, start by loading a DataTable instead of using a DataReader. With DataReader, as mentioned in the comments, you can iterate over the result set with a while loop

 while (reader.Read()) { } 

The loop reads one line at a time and exits when all lines have been read. When you move to the next line, the previous lines will no longer be available unless you place them in some other structure, such as a list or DataTable.

But you can use a DataAdapater to populate a DataTable, so there can be no reason to use a DataReader. Then you can write to the file from the DataTable.

In any case, I do not see how this line can work.

 FileName = Convert.ToString(reader["FileName"]) 

I can post additional code for any approach if you want.
HTH Harvey Sater

0
source

All Articles