有很多这样的代码块:
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,代码块也会增长。
谢谢..。
发布于 2013-02-01 18:06:02
using语句方法是上面提出的两种方法中最好的一种。使用这种方法,您可以确保ObjectContext在使用后被关闭和处理。
使用另一种方法时,可能会假设ObjectContext未关闭,因此会占用数据库的连接。要查看这一点,请尝试使用您的其他方法创建一个示例应用程序,然后使用EFProfiler分析它,并观察ObjectContext的打开数量上升,而闭包数量将显著减少。
我最近参与了一个项目,该项目采用了您的第二种模式,在高使用率下出现了数据库问题(您可以查看我关于它的问题,HERE)。由于我没有足够的时间进行项目/代码库太大,我没有选择切换到using语句方法。相反,我实现了以下代码来手动强制在Global.asax中的End_Request上处置ObjectContext (我在BusinessLayerService的静态实例上有一个DbContext实例
protected void Application_EndRequest(object sender, EventArgs e)
{
BusinessLayerService.Instance.Dispose();
BusinessLayerService.Instance = null;
}但是,如果您从项目开始就可以选择:,我强烈建议您使用 using pattern
发布于 2013-02-01 18:10:37
如果使用using-statement,在上面的示例中没有什么大问题,但是当dbContext是一个局部变量时,很难为这样的代码编写单元测试。
如果您不遵循任何设计模式,如存储库、工作单元,那么您不想编写单元测试,那么在这种情况下,使用语句将所有逻辑包装在中是最好的选择。
https://stackoverflow.com/questions/14643491
复制相似问题