Reputation: 892
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
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 :
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