Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to detect if an IDataReader is empty?

Tags:

c#

ado.net

It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?

like image 558
JC Grubbs Avatar asked Sep 09 '08 02:09

JC Grubbs


4 Answers

if(dr.Read())
{
   //do stuff
}
else
{
 //it's empty
}

usually you'll do this though:

while(dr.Read())
{
}
like image 122
Ben Scheirman Avatar answered Nov 14 '22 07:11

Ben Scheirman


Yes, if you want to use the interface then Read until false is the only way to test. If you are looking for a generic IDataReader implementation, you could try DbDataReader and use the HasRows property.

like image 31
JamesSugrue Avatar answered Nov 14 '22 09:11

JamesSugrue


You can just cast System.Data.IDataReader to System.Data.Common.DbDataReader

using (System.Data.IDataReader IReader = ICommand.ExecuteReader())
{
    if (((System.Data.Common.DbDataReader)IReader).HasRows)
    {
        //do stuff
    }
} // End Using IReader 

It's pure evil, but it (usually) works ;)

(assuming your instance of IDataReader is implemented by a custom ADO.NET provider, and not some custom silly class of yours which just implements IDataReader instead of deriving from DbDataReader [which implements IDataReader]).

like image 3
Stefan Steiger Avatar answered Nov 14 '22 09:11

Stefan Steiger


Just stumbled across this problem and came up with this...

bool isBeforeEoF;

do
{
    isBeforeEoF = reader.Read();

    if (isBeforeEoF)
    {
        yield return new Foo()
        {
            StreamID = (Guid)reader["ID"],
            FileType = (string)reader["Type"],
            Name = (string)reader["Name"],
            RelativePath = (string)reader["RelativePath"]
        };         
    }

} while (isBeforeEoF);
like image 2
SimonGates Avatar answered Nov 14 '22 07:11

SimonGates