Is it necessary to provide Entity Framework Context in the Using Statement?

c# entity-framework


The Dispose() function, which "Releases the resources utilized by the object context," is implemented by the Entity Framework context object. What exactly does it do? Putting it inside a using statement every time might be detrimental. Both with and without the using statement, I've seen it utilized.

I'll utilize the EF context explicitly from a WCF service method, build the context, do some linq, and then return the result.

EDIT: It seems that I'm not the only one who has this question. What what happens within the Dispose() procedure is a further concern. Some publications claim that it cuts connections, whereas others disagree. What's going on?

5/5/2009 11:58:28 AM

Accepted Answer

A context that you establish must be removed afterwards. If necessary, utilize theusing assertion is dependent on how long the context is present.

  1. You should actually utilize the context if you create it in a method and only use it inside that method.using because it provides exception handling to you without requiring any extra code.

  2. The execution duration of a method does not limit the life time of the context, therefore if you utilize the context for a longer amount of time, you cannot use theusing declaration, and you must dialDispose() Ensure that you constantly call it and look out for yourself.

What areDispose() do in the context of an object?

I didn't examine the code, but at the very least I anticipated that it would terminate the database connection and any associated sockets or other resources needed by the transport method.

5/5/2009 11:12:00 AM

Popular Answer

You may either directly dispose of the ObjectContext or wait for the garbage collector to do it, according to Writing Entity Framework Programs.

In conclusion, even though the using statement is not needed, it is best practice if you are aware that you have finished using the ObjectContext since the resource is released right away rather than having to wait for trash collection.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow