使用实体框架而不使用语句的缺点? [英] Drawbacks with using entity framework without using statement?
问题描述
有很多这样的代码块:
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中的 use-statement
或什么是最好的方法?另外,如果我们使用 using-statement
代码块生长。
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.
我最近在一个项目中使用了高水平的数据库问题,这个项目采用了你的第二种模式(你可以看到我的问题这里)。因为我没有足够的时间在项目/代码库太大,我没有选择切换到使用
语句方法。相反,我实现了以下操作来手动强制处理Global.asax中的 End_Request
中的 ObjectContext
(我有一个我的 BusinessLayerService
的静态实例上的 DbContext
的实例:
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屋!