Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

i have got error "There is already an open DataReader associated with this Command which must be closed first." while using DataReader using multiple command object. this is my to be using.

C#
using (SqlConnection conn = GetSQLConnectiion(repositoryID))
{
using (SqlCommand comm = new SqlCommand("select *from Content_Content", conn))
{
try
 {
 using (SqlDataReader reader = comm.ExecuteReader())
  {
  while (reader.Read() && currentDirectorySize > targetSize)
   {
   try
   {
    //do somthing....
  StringBuilder query = new StringBuilder("update Content_Content SET OnCache = 0 where ItemID = '");
  query.Append(ItemID.ToString());
  query.Append('\'');
  using (SqlTransaction transaction = conn.BeginTransaction(IsolationLevel.Serializable))
   {
   using (SqlCommand comm1 = new SqlCommand(query.ToString(), conn, transaction))
    {
    comm1.Transaction = transaction;
    count += comm1.ExecuteNonQuery();
    transaction.Commit();
      }
     }
    }
    catch
      {
      }
     }
    }
   }
  catch
    {
    }
 }
}


The error to be got in the using Sqltransaction the code is "using (SqlTransaction transaction = conn.BeginTransaction(IsolationLevel.Serializable))" . can anybody have an idea...

Thanks
karthikeyan Mathiyalagan.
Posted
Updated 13-Oct-13 23:43pm
v2

1 solution

This is because you forgot to close the DataReader and tried to execute another command to DB. Try closing reader just after it is not needed any more and before SqlTransaction transaction .

See this link for further explanation on this:

"There is already an open DataReader associated with this Command which must be closed first" explained[^]

Regards..
 
Share this answer
 
v3
Comments
Karthikeyan Mathiyalagan 14-Oct-13 5:59am    
Rohan,
The DataReader have more then one rows, so i have to update each row in second SqlCommand.if i closed DataReader the data will be closed than how to do?
Thanks7872 14-Oct-13 6:03am    
Get data some thing like suggested in this link: C# SqlDataAdapter.
Karthikeyan Mathiyalagan 14-Oct-13 8:21am    
we are already implemented as you suggested way to read the data from SqlReader.the data will store the collection table then close the reader.create new sqlcommend object to update. now we are change the implementation above the code. they expect like that. if it's possible any of fix for that.
Thanks7872 14-Oct-13 8:22am    
I am not getting what you say. There is ready made code available at the link i provided. If the problem is solved,accept this solution as answer using green button.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900