Is it possible to return an OleDb.OleDbDataReader object from a function?
If so how would you go about doing that?
My current code returns the data reader object but when I try to read that object I get an error saying System.InvalidOperationException: 'Invalid attempt to call Read when reader is closed.'
My code:
OleDbDataReader queryData = sendQueryReturnData("SELECT * FROM users WHERE username = ?;", Parameters);
while (queryData.Read()) //error on this line
{
//stuff
}
One way to keep
queryDatain-scope is to make it a field of anIDisposabletype and don't let any other method close it, like this:I put your code in
DoReadDataand the difference is thatqueryDatais now a field instead of a local variable.I also added some example code for
sendQueryReturnData. Notice that it assigns the results ofcommand.ExecuteReaderto thequeryDatafield. Don't useusinghere.Finally, implement the dispose pattern with
IDispose. The consequence of doing this is that whoever uses this class must now use ausingstatement or callDispose.That said, typically it's easier to just read the data from the database and close/dispose DB objects as soon as you're done. Instead, create a DTO that represents the data, populate and return a
List<MyDataDto>and then close/dispose resources. This reduces the ambiguity of when and who has responsibility for releasing those resources.