Question

string connectionString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
                const string query = "my Select query here";

                List<long> myList = new List<long>();
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    con.Open();
                    using (SqlCommand selectCommand = new SqlCommand(query, con))
                    {
                        selectCommand.CommandType = CommandType.Text;
                        SqlDataReader sqlreader = selectCommand.ExecuteReader();

                        while (sqlreader.Read())
                        {
                           long Id = (long)sqlreader["Id"];
                            List.Add(Convert.ToInt32(sqlreader[0].ToString()));

                            using (SqlCommand insertCommand = new SqlCommand("dbo.SP_Data", con))
                             {

                                 insertCommand.CommandType = CommandType.StoredProcedure;
                                 insertCommand.Parameters.Add("@Id", SqlDbType.BigInt).Value = Id;
                                 insertCommand.Parameters.Add("@StatusId", SqlDbType.BigInt).Value = 1;
                                 insertCommand.Parameters.Add("@ReportDate", SqlDbType.DateTime).Value = DateTime.Now;
                                 insertCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = DateTime.Now;
                                 insertCommand.Parameters.Add("@CreatedBy", SqlDbType.UniqueIdentifier).Value = DefaultUser();

                                 insertCommand.ExecuteNonQuery();
                             }
                        }
                    }
                }

I am getting the error "There is already an open DataReader associated with this Command which must be closed first." at the last line [insertCommand.ExecuteNonQuery();

Was it helpful?

Solution

You need to enalbe MARS in your connection string (MARS = Multiple Active Result Sets)

In short, this particular flag, when enabled in the connection string, allows to use the same connection used by the SqlDataReader also for executing commands. Otherwise, as stated by MSDN the connection is busy serving the SqlDataReader and cannot execute other commands.
Before Sql Server 2005 the developpers were forced to create, open and use another connection. (Still possible if your environment doesn't allow to change the connection string)

More info about MARS could be found on this MSDN article
Examples of connection string that uses MARS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top