How to detect EOF on DataReader in C # without executing Read ()

I am familiar with using .Read () to detect EOF

        using (IDataReader reader = SqlHelper.ExecuteReader(_connectionString, "dbo.GetOrders"))
        {
            AssertOrder(reader);

            while (reader.Read())
            {
                yield return FillRecord<Order>(reader, StringComparer.OrdinalIgnoreCase);
            }
            reader.Close();
        }

Due to some strange situation that I got into, FillRecord actually promotes the reader. So now .Read () in the while loop actually forces this function to skip some lines - because we are moving twice.

I'm sorry there was no IDataReader.EOF, but no. Any thoughts?

+5
source share
3 answers

I think I probably expressed my opinion in the comments ... but since you asked for "Any Thoughts" ... here ya go:

Obviously, two seconds hack work, but you get the idea:

( IDisposable ( , IDataReader - ?) .. , IDataReader . -, .

public class DataReaderWithEOF
{
     public bool EOF { public get; private set; }
     private IDataReader reader;

     public DataReaderWithEOF(IDataReader reader)
     {
          this.reader = reader;
     }

     public bool Read()
     {
           bool result = reader.Read();
           this.EOF = !result;
           return result;
     }
}
+4
using (IDataReader reader = SqlHelper.ExecuteReader(_connectionString, "dbo.GetOrders"))
    {
         if(!reader.HasRows)
         {
              Response.Write("EOF"); // empty
         }
         while (reader.Read()) //read only registers
         {
               yield return FillRecord<Order>(reader, StringComparer.OrdinalIgnoreCase);
          }
          reader.Close();
       }
    }

, a. () . do if (reader.Read()) u .

+1

An alternative to Steve's solution is to call reader.Close () in FillRecord when Read () returns false. Then you can check reader.IsClosed in your main loop.

0
source

All Articles