使用实体框架,而不使用语句缺点? [英] Drawbacks with using entity framework without using statement?
问题描述
有很多code块是这样的:
There a lot of code blocks like this:
public class SomeController : Controller
{
DbEntities entity = new DbEntities();
public ActionResult Add()
{
entity.someOperations...
return View();
}
public ActionResult Edit()
{
entity.someOperations...
return View();
}
public ActionResult Detail()
{
entity.someOperations...
return View();
}
public ActionResult Detail()
{
entity.someOperations...
return View();
}
.....
我应该改变这样的方式:
Should I change the methods like this?:
public class SomeController : Controller
{
public ActionResult Add()
{
using(DbEntities entity = new DbEntities())
{
entity.someOperations...
}
return View();
}
.....
什么是与不使用使用语句
EF中的问题?或什么是最好的方式?另外,如果我们使用使用语句
code块生长。
What are the problems with not using using-statement
in EF? OR what is the best way? Also, If we use using-statement
code blocks are grown.
谢谢...
推荐答案
使用语句的方法是最好的,你在上面提出的两个。使用这种方法,你可以放心的的ObjectContext
关闭和处置它的使用后。
The using
statement approach is the best of the two that you have proposed above. Using this approach, you can be assured that the ObjectContext
is closed and disposed of after it's use.
使用您的另一种方法,人们会假定的ObjectContext
可留给未闭合,因此占用与数据库的连接。要看到这个动作,尝试创建与其他方法的一个示例应用程序,然后使用配置文件它 EFProfiler 看着的ObjectContext
的崛起打开,而关闭的数量将明显变小。
Using your other approach, one would assume that the ObjectContext
could be left unclosed, therefore hogging connections to the database. To see this in action, try creating a sample app with your other approach, then profile it using the EFProfiler and watch the number of ObjectContext
's opened rise, whilst the number of closures will be notably smaller.
最近,我在这是有根据的高水平采纳了你的第二个模式使用的数据库问题的一个项目工作(你可以看到我的疑问的<一个href=\"http://stackoverflow.com/questions/12729429/entity-framework-closure-of-object-contexts\">HERE).由于我没有足够的时间对项目/ code基太大,我没有切换到使用
语句的方法的选择,而是我采取了以下手动强制在 END_REQUEST
处置的的ObjectContext
在Global.asax中(我有一个实例的的DbContext
上的静态实例我的 BusinessLayerService
:
I recently worked on a project that was having database issues under high levels of usage that adopted your second pattern (you can see my question about it HERE). As I didn't have enough time on the project/code base was too large, I didn't have the option to switch to the using
statement approach. Instead I implemented the following to manually force the disposal of the ObjectContext
on the End_Request
in Global.asax (I had an instance of the DbContext
on a static instance of my BusinessLayerService
:
protected void Application_EndRequest(object sender, EventArgs e)
{
BusinessLayerService.Instance.Dispose();
BusinessLayerService.Instance = null;
}
但是,如果你从项目开始的选项:我会强烈建议使用使用
模式
But if you have the option from the project start: I would highly recommend using the using
pattern
这篇关于使用实体框架,而不使用语句缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!