在实体框架明确地关闭连接 [英] Closing connections explicitly in Entity Framework

查看:151
本文介绍了在实体框架明确地关闭连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Microsoft文档 http://msdn.microsoft.com/en-us/library/bb738684的.aspx 我看到他们明确地打开和关闭连接

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?

推荐答案

这是不使用EF的正常的方式。 EF通常为您管理的连接。但是:

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

在管理对象服务(实体框架)

对象服务连接暴露出的 EntityConnection 的借指在连接的的属性。这使您可以管理连接和交易,或提供自己的 EntityConnection 的。当你想打开抱一个短命的对象范围内的连接,以提高性能或明确地控制交易,这非常有用。通过实体框架使用相同的供应商连接可以与应用程序的其它部分共享

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.

如果您手动打开连接,对象背景不会关闭它。调用Close或Dispose将关闭连接。

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.

如果你提供一个开放的 EntityConnection 的为对象范围内,你必须确保它被设置。

If you supply an open EntityConnection for the object context, you must ensure that it is disposed.

因此,在短期,通常你不管理的连接,但如果你想为上述原因做手工,你可以。如果您决定手动打开连接,你需要手动关闭它(如果你决定去手动EF不作任何假设你)。

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).

这篇关于在实体框架明确地关闭连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆