The Entity Framework context object implements a Dispose() method which “Releases the resources used by the object context”. What does it do really? Could it be a bad thing to always put it into a using {} statement? I’ve seen it being used both with and without the using statement.
I’m specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.
EDIT: Seems that I’m not the only one wondering about this. Another question is what’s really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What’s the deal?
If you create a context, you must dispose it later. If you should use the
usingstatement depends on the life time of the context.If you create the context in a method and use it only within this method, you should really use the
usingstatement because it gives you the exception handling without any additional code.If you use the context for a longer period – that is the life time is not bound by the execution time of a method – you cannot use the
usingstatement and you have to callDispose()yourself and take care that you always call it.What does
Dispose()do for an object context?I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.