简体   繁体   English

实体框架和数据库连接

[英]Entity Frameworks and database connections

I was debugging Jaroslaw Kowalski provider wrappers. 我正在调试Jaroslaw Kowalski提供程序包装器。 While debugging it I observed that the Entity Framework closes the connection after every query. 调试时,我观察到实体框架在每次查询后都会关闭连接。 On every interaction with database, during the lifetime of application, a database connection is opened and after performing the query the connection is closed 在与数据库的每次交互中,在应用程序的生存期内,将打开数据库连接,并在执行查询后关闭连接

My questions are: 我的问题是:

  • Whether the underlying provider do connection pooling by default. 默认情况下,基础提供程序是否进行连接池。
  • If I provide my own pooling then how will I know when to close the connection. 如果我提供自己的缓冲池,那么我将如何知道何时关闭连接。 At the moment I am registering with Thread.GetDomain().ProcessExit event and closing the connection when the event fires. 目前,我正在注册Thread.GetDomain()。ProcessExit事件,并在事件触发时关闭连接。 Is this approach good? 这种方法好吗?

The thing that is bothering me is that Entity Framework itself is closing the connection. 困扰我的是实体框架本身正在关闭连接。 So I am a little hesitant to pool the connection or it may cause problems in exceptional scenarios. 所以我有点犹豫要合并连接,否则在特殊情况下可能会引起问题。

FYI: 仅供参考:

The EF only closes connections it opens. EF仅关闭其打开的连接。

So if you do something like this manually: 因此,如果您手动执行以下操作:

((ctx.Connection as EntityConnection).StoreConnection as SqlConnection).Open();

subsequents queries and SaveChanges() shouldn't close that connection. 后续查询和SaveChanges()不应关闭该连接。

Hope this helps 希望这可以帮助

Alex 亚历克斯

The default connectionpool = 1 connection. 默认连接池= 1个连接。 So don't worry. 所以不用担心

The whole idea here is that we have 1 programming model (disconnected) and that configuration & tuning is external. 这里的整个想法是,我们有1个编程模型(已断开连接),并且配置和调整是外部的。

In .Net 4, to quote: Managing Connections and Transactions 在.Net 4中,引用: 管理连接和事务

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. 如果为对象上下文提供开放的EntityConnection,则必须确保将其处置。

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

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