What is the best way to determine if IDataReader is empty?

It seems that IDataReader.Read () is always true at least once (if I am wrong about this, let me know.) So, how do you know if it has entries without wrapping them in try / catch

+5
source share
4 answers
if(dr.Read())
{
   //do stuff
}
else
{
 //it empty
}

usually you will do it though:

while(dr.Read())
{
}
+14
source

Yes, if you want to use the interface, then read it until it becomes the only validation method. If you are looking for a universal implementation IDataReader, you can try DbDataReaderand use a property HasRows.

+4
source

System.Data.IDataReader System.Data.Common.DbDataReader

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

, () ;)

(assuming your instance is IDataReaderimplemented by a custom ADO.NET provider, not some kind of custom stupid class that only implements IDataReaderinstead of fetching from DbDataReader[which implements IDataReader]).

+2
source

Just stumbled upon 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);
+2
source

All Articles