K09
K09

Reputation: 201

Connection Not Closed Error

Why do I get this error when running the below code? This happens regularly. I have a check for open connections in place...

System.InvalidOperationException: The connection was not closed.
   at System.Data.EntityClient.EntityConnection.Open()
   at Publish(Int32 reportID)

CODE:

while (!completed && 5 >= retryCount)
{
   retryCount++;
   try
   {
       internalReportsEntities.CommandTimeout = (5 * 60);
       internalReportsEntities.Publish(internalSet.ID); // publish method called
       completed = true;
   }
   catch (EntityCommandExecutionException entityCommandExecutionException)
   {
        if (5 < retryCount) throw;
        Utilities.ThreadUtilities.Sleep(retryCount);
   }
}

public void Publish(int reportID)
{
if (this.Connection.State != System.Data.ConnectionState.Open) this.Connection.Open();
EntityCommand publishEntityCommand = new EntityCommand
    {
            CommandType = CommandType.StoredProcedure,
            CommandText = @"ReportsEntities.Publish",
            Connection = (EntityConnection)this.Connection
    };
}

Upvotes: 0

Views: 67

Answers (1)

Stephen Wilson
Stephen Wilson

Reputation: 1514

You will need to wrap the code in your Publish method in a try / catch / finally block and dispose of the connection when you are finished with it. A great example is explained here: http://msdn.microsoft.com/en-gb/library/vstudio/bb738461(v=vs.100).aspx

Upvotes: 1

Related Questions