Entity Framework intentionally closes connections

c# entity-framework


http://msdn.microsoft.com/en-us/library/bb738684.aspx Reading the Microsoft docs They clearly open and shut the connection, as I can see.

using (EntityConnection conn = new EntityConnection("name=AdventureWorksEntities"))

Why is this required?

3/12/2011 10:20:28 PM

Accepted Answer

This isn't how EF is "normally" used. EF typically handles connection management for you. However:

Connections Management in Object Services (Entity Framework)

Object Services exposes the EntityConnection by means of the Connection property. This enables you to manage the connection and transactions or to supply your own EntityConnection. This is useful when you want to hold open a connection within a short-lived object context to improve performance or to explicitly control transactions. The same provider connection used by the Entity Framework can be shared with other parts of an application.

The following considerations apply when managing connections:

  • The object context will open the connection if it is not already open before an operation. If the object context opens the connection during an operation, it will always close the connection when the operation is complete.

  • If you manually open the connection, the object context will not close it. Calling Close or Dispose will close the connection.

  • If the object context creates the connection, the connection will always be disposed when the context is disposed.

  • In a long-running object context, you must ensure that the context is disposed when it is no longer required.

  • If you supply an open EntityConnection for the object context, you must ensure that it is disposed.

In summary, you don't often control the connection, although you may if you wish to for the reasons mentioned above. The connection must be closed manually if you want to manually open it (EF won't assume anything if you choose to go this route).

2/8/2013 9:07:02 PM

Popular Answer

It is unnecessary due toDispose handled by the using statement that is called. However, it is a good practice to call clearly.Close once you're aware that connection won't be required going forward. For instance, you wish to release database connection covered by entity connection as soon as possible since you are unsure of how difficult the disposal is.

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