简体   繁体   English

Linq到实体ObjectContext和数据库连接

[英]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. 我总是看到很多有关如何处理EF上下文生命周期的问题,但从未找到具体的答案。

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). 因此,假设在一个程序中我们创建了一个类来管理所有常见的数据库任务(创建用户,更新用户,删除用户等),并且在每个程序中我们都创建了一个包装在using语句中的上下文,该上下文旨在使用(至少在我找到的所有信息上)。

So, now, in our main program in a function we use, let's say, 3 or 4 of those functions. 因此,现在,在我们的主程序中使用的功能,假设使用其中的3个或4个。 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? 这是否意味着我们已经打开和关闭了与数据库的四个连接,或者EF是否使用池化机制来重用同一连接?

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. 连接到数据库是一个非常耗时的过程(与执行简单查询相比),当使用手动连接时,我倾向于将它们合并以重用,但是由于使用了EF,我迷路了,不知道是否应该合并上下文,合并连接并创建使用该连接的上下文或不执行任何操作,因为EF会照顾它。

If all your EF instances share the same connection string, then by default it uses a connection pool. 如果您的所有EF实例共享相同的连接字符串,则默认情况下它将使用连接池。 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.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an- ASP净MVC应用程序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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