如果实体框架范围内投入使用的声明? [英] Should Entity Framework Context be Put into Using Statement?

查看:123
本文介绍了如果实体框架范围内投入使用的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体框架上下文对象实现了其版本中使用对象上下文的资源一Dispose()方法。它有什么作用真的吗?难道是一件坏事总是把它变成一个使用{}语句?我已经看到了同时使用有和没有使用的语句。

The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement.

我专门去一个WCF服务方法中使用的EF背景下,从创建的背景下,做一些LINQ和返回答案。

I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.

编辑:看来我不是唯一一个知道这件事。另外一个问题是什么的Dispose()方法中真的发生了。有人说,它关闭连接,有的文章说不行。这是怎么回事?

Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?

推荐答案

如果您创建一个环境,你以后必须处理它。如果您应该使用使用语句取决于上下文的续航时间。

If you create a context, you must dispose it later. If you should use the using statement depends on the life time of the context.


  1. 如果您创建一个方法的上下文,只有在这个方法中使用它,你应该使用使用语句,因为它可以让你的异常处理,而不任何额外的code。

  1. If you create the context in a method and use it only within this method, you should really use the using statement because it gives you the exception handling without any additional code.

如果您使用较长时间的情况下 - 这是企业的生命时间不是由一个方法的执行时间限制 - 你不能使用使用声明,你要叫的Dispose()自己和照顾,你总是称呼它。

If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the using statement and you have to call Dispose() yourself and take care that you always call it.

这是什么的Dispose()为对象范围内呢?

What does Dispose()do for an object context?

我没看code,但至少我ExSpect语言它关闭与任何资源使用的传输机制,其标的插座或数据库连接。

I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.

这篇关于如果实体框架范围内投入使用的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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