繁体   English   中英

使用实体框架而不使用语句的缺点?

[英]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();
    }

    .....

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

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

        return View();
    }
    .....

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

谢谢...

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

如果你不遵循任何设计模式,如Repository,Unit of Work,你不想编写单元测试,那么在using case中包装所有逻辑是这种情况下的最佳选择。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM