Entity Framework intentionally closes connections

c# entity-framework

Question

Reading the microsoft documentation http://msdn.microsoft.com/en-us/library/bb738684.aspx I see they explicitly open and close the connection

using (EntityConnection conn = new EntityConnection("name=AdventureWorksEntities"))
{ 
    conn.Open();
    ...
    conn.Close();
}

why is this necessary?

1
15
3/12/2011 10:20:28 PM

Accepted Answer

This isn't the "normal" way of using EF. EF usually manages the connection for you. However:

Managing Connections 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.

So in short, normally you don't manage the connection, but if you want to do it manually for the reasons stated above, you can. If you decide to open the connection manually, you need to close it manually (EF doesn't make any assumptions for you if you decide to go manual).

29
2/8/2013 9:07:02 PM

Popular Answer

It is not necessary because Dispose invoked by using statement will handle it. But it is good habit to explicitly call Close once you know that connection will not be needed any more. For example you don't know how complex the disposal is so you want to free database connection wrapped by entity connection as soon as possible.



Related Questions





Related

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