The 'Connection' object can be discarded more than once in the method

Asked

Viewed 185 times

2

Follows the code:

public ActionResult Index(ViewModel model, string returnUrl)
{
    string query = "UPDATE Table SET Status = 'C' WHERE Id = @Num";

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.Add("@Num", SqlDbType.Int).Value = model.Numero;
        connection.Open();
        command.ExecuteNonQuery();
        connection.Close();
    }
    return RedirectToAction("Page", "Account");
}

I get a warning in the bug lists:

CA2202: The 'Connection' object can be discarded more than once in the method 'Accountcontroller.Index(Viewmodel, string)'. To avoid generating System.Objectdisposedexception, do not call Dispose more than once on an object.

Some solution?

1 answer

3


Just take the explicit closure of the connection, after all it is doing right with the using that will close the connection.

public ActionResult Index(ViewModel model, string returnUrl) {
    var query = "UPDATE Table SET Status = 'C' WHERE Id = @Num";
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (var command = new SqlCommand(query, connection)) {
        command.Parameters.Add("@Num", SqlDbType.Int).Value = model.Numero;
        connection.Open();
        command.ExecuteNonQuery();
    }
    return RedirectToAction("Page", "Account");
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.