Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error 'there is already an open datareader associated with this command which must be closed first'

Tags:

c#

ado.net

runtime error 'there is already an open datareader associated with this command which must be closed first'

objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);

objDataReader = objCommand.ExecuteReader();

while (objDataReader.Read())
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')", objConn);
objInsertCommand.ExecuteNonQuery();//Here is the error
}
objDataReader.Close();

I cannot define any stored procedure here. Any help would we appreciated.

like image 600
Pradeep Avatar asked Sep 09 '25 12:09

Pradeep


1 Answers

No need to do all that, just turn on MARS and your problem will get solved. In your connection string just add MultipleActiveResultSets=True;

like image 84
ali Avatar answered Sep 11 '25 01:09

ali