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

若如初见. 提交于 2019-12-23 12:16:10

问题


I'm familiar with using .Read() to detect the 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 weird situation I got myself into, the FillRecord actually advances the reader. So now the .Read() in the while loop actually causes this function to skip some rows -- because we are advancing twice.

I wish there was an IDataReader.EOF, but there isn't. Any thoughts?


回答1:


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

Obviously a two second hack job, but you'll get the idea:

(You'd surely want to implement IDisposable (since I think IDataReader is??) etc. Probably just make the class inherit from IDataReader, and implement the class as a facade. Or get real cool and implement a transparent proxy which hijacks the Read method.

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;
     }
}



回答2:


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();
       }
    }

every time u use a. Read () it next record. then do if(reader.Read()) u would already be advancing a record.




回答3:


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.



来源:https://stackoverflow.com/questions/7844355/how-to-detect-eof-on-datareader-in-c-sharp-without-executing-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!