Search code examples
c#asp.net-web-apisql-server-mars

Open DataReader, Must be Closed: Works Locally, Fails Deployed. WEB API


The following code works fine when debugging locally. Whenever I push it up to my development server, it doesn't work anymore. I've found the bit of code that causes the problem and I was able to fix by adding the line that has a comment below but I'm not sure why I had to add the line. In the Web.Config, I have MultipleActiveResultSets=true; which should cause this not to happen. So, I'm unsure why I have to add this line.

public bool PersistStuff(string Account, List<Acknowledgement> acks)
{
    string sql = "my.sp.AccountProcedure";

    bool retVal = true;

    using (SqlConnection conn = new SqlConnection(_accountConnection))
    {
        conn.Open();

        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@Account", System.Data.SqlDbType.VarChar, 50)).Value = Account;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    int id = int.Parse(reader[0].ToString());

                    //*************************
                    // This is the line I added

                    reader.Close();

                    //*************************

                    sql = "my.sp.AccountAcknowledgementProcedure";

                    using (SqlCommand cmd2 = new SqlCommand(sql, conn))
                    {
                        cmd2.CommandType = System.Data.CommandType.StoredProcedure;

                        foreach (Acknowledgement item in acks)
                        {
                            cmd2.Parameters.Clear();

                            cmd2.Parameters.Add(new SqlParameter("@severity", System.Data.SqlDbType.VarChar, 25)).Value = item.Severity.ToString();

                            if (!string.IsNullOrEmpty(item.ErrorData))
                                cmd2.Parameters.Add(new SqlParameter("@errorData", System.Data.SqlDbType.VarChar, 500)).Value = item.ErrorData;
                            else
                                cmd2.Parameters.Add(new SqlParameter("@errorData", System.Data.SqlDbType.VarChar, 500)).Value = DBNull.Value;

                            cmd2.ExecuteNonQuery();
                        }
                    }
                }
                else
                {
                    retVal = false;
                }
            }
        }
    }

    return retVal;
}

Solution

  • As I was writing the question, I forgot I had xdt:Transforms in my Web.Debug.Config and Web.Release.Config. After looking at my Debug and Release configs, neither had MultipleActiveResultSets=true; in the connection string used. I changed the connection strings in each config to have it and redeployed and everything worked fine.