简体   繁体   中英

Linq to Entities ObjectContext and DB connections

I always have seen lots of questions about how to handle the life-cycle of an EF context, but never found a concrete answer to this.

As stated everywhere, context is intended to be used as a unit work and be disposed whenever you finish that work.

So, let's suppose in a program we create a class to manage all the tipical database tasks (create user, update user, delete user, etc..) and in each one we create a context wrapped into a using statement as is intended to be used (at least on all info I have found).

So, now, in our main program in a function we use, let's say, 3 or 4 of those functions. Does that mean we have opened and closed four connections to the database or does EF uses a pooling mechanism to reuse the same connection?

Connecting to the DB is a very consuming process (compared to execurte simple queries) and when using manually connections I tend to pool them to reuse, but with EF I am lost, don't know if I should pool contexts, pool connections and create contexts using that connections or do nothing as the EF will take care of it.

If all your EF instances share the same connection string, then by default it uses a connection pool. However, I would recommend you to read about the Unit of Work pattern

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

http://www.codeproject.com/Articles/615499/Models-POCO-Entity-Framework-and-Data-Patterns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM