0

使用像这两种方法这样的上下文有什么区别

public class MyController : Controller
{
    MyContext db = new MyContext();

    public ActionResult Index()
    {
        return View(db.Users.First(m => m.Id == 1));
    }
    // ...
}

或者

public class MyController : Controller
{
    public ActionResult Index()
    {
        using (MyContext db = new MyContext())
        {
            return View(db.Users.First(m => m.Id == 1));
        }
    }
    // ...
}
4

2 回答 2

3

首先,上下文在类范围内可用。它在初次使用后也永远不会被正确处理(至少在你给我们的代码的上下文中是这样)。

第二,上下文在using块内实例化。在块之后,上下文被正确处理。

于 2013-06-21T17:59:04.667 回答
1

仅供参考,这是在控制器级别创建时如何处理 db 上下文:

public class MyController : Controller
{
    MyContext db = new MyContext();

    public ActionResult Index()
    {
        return View(db.Users.First(m => m.Id == 1));
    }
    // ...

    // This is automatically called by the framework, after
    // the ActionResult.ExecuteResult() is called.
    protected override void Dispose(bool disposing)
    {
        if (disposing && db != null)
        {
            db.Dispose();
        }

        base.Dispose(disposing);
    }
}

视图执行后调用控制器的 Dispose 方法。这将允许您调用视图中的任何延迟属性(IQueryables,延迟加载的属性)。在操作中处理 dbcontext 不允许这样做(第二个示例)。在第二个示例中,任何对延迟操作的引用都会给您一个例外。

于 2013-06-21T18:17:34.910 回答