0

I am trying to pass data reader to a method but getting error like below :

Invalid attempt to call fieldcount when reader is closed.

Code :

public class ImportService
{
    public IDataReader Reader { get; set; }
    public void MyMethod() 
    {
       string[] Tables = { "Table1", "Table2"};
       foreach (var table in Tables)
       {
          try
           {
                var msSql = new MsSql(table,conn);
                Reader = msSql.Reader;
                msSql.Reader.Close();
                DumpData(conn, Reader);
                Reader.Close();
           }
           catch (Exception ex)
           {
                 //catch exception here
                 Reader.Close();//in case of error while dumping data close the reader.
           }
       }

       conn.close();
   }

   private void DumpData(SqlConnection conn, IDataReader reader) //Invalid attempt to call FieldCount when reader is closed
   {
   }
}

public class MsSql
{
     public IDataReader Reader { get; set; }
     public MsSql(string table, SqlConnection Conn)
     {
             GetData(table,Conn);
     }
     private void GetData(string table, SqlConnection Conn)
     {
        string query = "SELECT * FROM " + table;
        using (SqlCommand cmd = new SqlCommand(query, Conn))
        {
            cmd.CommandTimeout = 0;
            Reader = cmd.ExecuteReader();
        }
     }
}

I am successfully getting data in my global object Reader but when I pass it to my dumpdata method I get an error.

I have already checked the below questions, but they couldn't help me with my current scenario :

Update: When I pass msSql.Reader to Dumpdata then everything works fine like below:

DumpData(conn, msSql.Reader);
halfer
  • 19,824
  • 17
  • 99
  • 186
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216

1 Answers1

2

What you are doing is this:

  1. Retrieving the Reader Reader = msSql.Reader;
  2. Closing the self-same Reader msSql.Reader.Close();
  3. Attempting to read data from the, now closed, Reader: DumpData(conn, Reader)

So you are trying to read from a closed reader (that's presumably what DumpData() does - and get a corresponding message.

I think you are labouring under the mis-apprehension that by assigning the same object to another variable you are creating another object. This is not so. You are merely referencing it from more than one point.

So: msSql.Reader and the local Reader both refer to the same object.

Jens Meinecke
  • 2,904
  • 17
  • 20