Strawberry Farmer
Strawberry Farmer

Reputation: 892

how do you check open entity framework connections

In Entity Framework 5 with VS2012/VS2013. C#

Given the following:

using (modelEntities context = new modelEntities())
{
    //do stuff
    context.Dispose();
}

The using statement is suppose to call Dispose() on its own. I still call dispose on the connection just to make sure its being closed. Is there a way to check if there open connections on my Visual Studio project running on localhost?

Edit: I have placed context.Dispose(); inside of the using block. That is the way I wanted to show it. Now it will compile.

Upvotes: 3

Views: 4277

Answers (1)

rism
rism

Reputation: 12132

A DbContext has a Database property of type IDbConnection which in turn has a State property of type System.Data.ConnectionState which is an enumeration.

The values for ConnectionState enumeration are :

  • Broken The connection to the data source is broken. This can occur only after the connection has been opened. A connection in this state may be closed and then re-opened. (This value is reserved for future versions of the product.)
  • Closed The connection is closed.
  • Connecting The connection object is connecting to the data source.
  • Executing The connection object is executing a command. (This value is reserved for future versions of the product.)
  • Fetching The connection object is retrieving data. (This value is reserved for future versions of the product.)
  • Open The connection is open.

MSDN Connection State

However merely doing a get on the DbContext.Database can in fact open the connection. You would be better off trusting the using wrapper to properly dispose of your context, rather than calling context.Dispose() again, simply because Microsoft's code has likely been tested to a much greater extent than yours or mine ever will be.

If you absolutely must explicitly ensure the connection is closed then you could override the Dispose method of your context and call

context.Close();

which

closes the connection to the database. This is the preferred method of closing any open connection.

By calling context.Dispose again after the using statement, you are basically communicating to anyone that reads your code that you have / or had a problem that you haven't actually debugged and that you are just randomly calling clean up code that you "hope" works.

Edit : As per the comment this wont even compile due to scope. I misread your question in this regard, if you are passing in the context to a repository or as part of a unit of work as is how I typically do it and then decide to close out your context with a using then you should just trust that it going to be cleaned up as per.

Upvotes: 1

Related Questions