The 'connection' object can be dropped more than once in the method

2

Follow 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 error lists:

  

CA2202: Connection object can be dropped more than once in method   'AccountController.Index (ViewModel, string)'. To prevent the generation of   System.ObjectDisposedException, do not call Dispose more than once in   an object.

Any solution?

    
asked by anonymous 07.05.2017 / 05:09

1 answer

3

Just take the explicit closing 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 placed it on GitHub for future reference .

    
07.05.2017 / 07:22