使用entity framework而不使用语句的缺点?

有很多像这样的代码块:

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(); } ..... 

我应该改变这样的方法吗?:

 public class SomeController : Controller { public ActionResult Add() { using(DbEntities entity = new DbEntities()) { entity.someOperations... } return View(); } ..... 

在EF中不使用using-statement有什么问题? 或者最好的方法是什么? 另外,如果我们使用using-statement代码块也会增长。

谢谢…

using声明方法是您在上面提出的两种方法中最好的。 使用这种方法,可以确保ObjectContext在使用后关闭并处理掉。

使用您的其他方法,可以假设ObjectContext可以保持未闭合,从而占用与数据库的连接。 要查看此操作,请尝试使用其他方法创建示例应用程序,然后使用EFProfiler对其进行概要分析,并观察ObjectContext打开的数量,同时闭包数量会明显减少。

我最近参与了一个项目,该项目在高使用率下遇到了数据库问题,采用了你的第二种模式(你可以在这里看到我的问题)。 由于我没有足够的时间在项目/代码库上太大,我没有选择切换到using语句方法。 相反,我实现了以下操作来手动强制在Global.asax中的DbContext上处理ObjectContext (我在DbContext的静态实例上有一个DbContext实例:

 protected void Application_EndRequest(object sender, EventArgs e) { BusinessLayerService.Instance.Dispose(); BusinessLayerService.Instance = null; } 

但是,如果您从项目开始有选项: 我强烈建议使用using模式

如果使用using语句,上面的示例中没有大问题,但是当dbContext是局部变量时,很难为这样的代码编写unit testing。

如果你不遵循任何设计模式,如Repository,Unit of Work,你不想编写unit testing,那么在这种情况下将using语句中的所有逻辑包装起来是最好的选择。