在不使用using语句的情况下使用实体框架存在哪些缺点?

3

有很多这样的代码块:

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,代码块会变得更长。

谢谢...

2个回答

5

如果使用using语句,那么上面的例子中没有大问题,但是对于像dbContext这样的局部变量编写单元测试非常困难。

如果您不遵循任何设计模式(如Repository、Unit of Work),也不想编写单元测试,则在using语句中包装所有逻辑是在这种情况下最好的选择。


@phnkha,你能否提供一个好的关于Repository和Unit of Work实现的参考资料? - Arun Prasad E S

2
using语句的方法是你上面提出的两种方法中最好的方法。使用这种方法,可以确保在使用后关闭和处理ObjectContext
使用您的其他方法,人们可能会认为ObjectContext可能未被关闭,因此占用了与数据库的连接。要查看此操作,请尝试使用您的其他方法创建示例应用程序,然后使用EFProfiler进行配置文件,并观察打开的ObjectContext的数量增加,而关闭的数量将明显较小。
我最近参与了一个项目,在高使用率下遇到了数据库问题,采用了您的第二种模式(您可以在这里看到我的问题)。由于我没有足够的时间来处理该项目/代码库太大,因此我无法选择使用using语句的方法。相反,我在Global.asax中的End_Request上实现了以下内容,以手动强制处理ObjectContext的处理(我在我的BusinessLayerService的静态实例上有一个DbContext的实例)。
protected void Application_EndRequest(object sender, EventArgs e)
    {
        BusinessLayerService.Instance.Dispose();
        BusinessLayerService.Instance = null;
    }

但如果您从项目开始就有选择的话:我强烈建议使用using模式


我明白了,非常感谢。但是我想知道,我的第一个例子有什么问题。未来会出现什么问题... - AliRıza Adıyahşi
@AliRızaAdıyahşi 没问题,问题在于有时你无法确定与数据库的连接是否已经关闭(即 ObjectContext 是否已关闭)。由于 using 语句在 ObjectContext 上调用了 .Dispose(),所以当使用 using 语句时可以确保它被销毁。 - Mathew Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接