Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Entity Framework open and close Database Connections?

When I instance my "Entities" object in Entity Framework, and make a couple of queries using that Entities object, what happens to connections?

  • Does it open a connection when I instance the object, and close it when I dispose of it?
  • Or does it open and close a connection for each single query I execute?

In either case, is it possible to change it so that it does the other thing?

like image 223
Daniel Magliola Avatar asked Aug 15 '09 19:08

Daniel Magliola


People also ask

How does Entity Framework manage connections?

Entity Framework manages a connection pool, which means that EF will reuse connections when possible and only create new ones when it needs to. Whether or not each call creates a new connection depends on many factors. So it's hard to say whether any given set of calls will or will not create new connections.

How does Entity Framework affect the connection with the database?

Because an open connection to the database consumes a valuable resource, the Entity Framework opens and closes the database connection only as needed. You can also explicitly open the connection. For more information, see Managing Connections and Transactions. Once in each application domain.

How do you close a connection in Entity Framework?

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.


1 Answers

Basically it opens when a request is called and closes once the results have been disposed or consumed. You can manually open/close or use the same connection using the object context...

This article has a more complete explanation - http://msdn.microsoft.com/en-us/library/bb738582.aspx (archive.org)

Here is the How To on using an entity Connection - http://msdn.microsoft.com/en-us/library/bb738461.aspx (archive.org)

like image 123
Kelly Robins Avatar answered Sep 22 '22 06:09

Kelly Robins