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