我试图对以下问题写出完整详细的答案:为什么“Dispose”有效,而不是“using(var db = new DataContext())”? https://stackoverflow.com/questions/23110719/why-does-dispose-work-and-not-usingvar-db-new-datacontext
所以我建立了我的项目,其中包括:
使用实体框架的部门和员工
所以我的行动方法是这样的:
public ActionResult Index()
{
IEnumerable<department> d;
using (var ctx = new ApplicationDbContext())
{
d = ctx.departments;
}
return View(d);
}
很自然地预期这会导致常见错误:
The operation cannot be completed because the DbContext has been disposed
当我想解决它时,我执行了以下操作[强制急切加载而不是轻松加载]:
public ActionResult Index()
{
IEnumerable<department> d;
using (var ctx = new ApplicationDbContext())
{
d = ctx.departments.toList();
}
return View(d);
}
所以我试图了解幕后的事情并查看 View() 方法的返回类型。我达到了以下目的'Correct' 假设:
1-模型 [d] 在 using 语句中以延迟加载方式调用。
2-因此,当模型 [d] 发送到视图以生成页面时,DbContext 已由 using 语句的最后一个大括号处理。
3-我们通过使用急切加载方式将模型 [d] 发送到视图来解决这种情况。
然后我继续我的假设,事实证明是'wrong'如下:
4-由于 View() 方法返回 ViewResult 对象,它也是一个 ActionResult ..那么我可以在 using 语句中生成该对象,然后将其返回给用户。
所以我做了以下事情:
public ActionResult Index()
{
ActionResult myView;
using (var ctx = new ApplicationDbContext())
{
IEnumerable<department> d = ctx.departments;
myView = View(d);
}
return myView;
}
所以我现在告诉自己,当我运行它时,ViewResult 对象 [ myView] 将已经创建并将返回给用户,并且不会遇到错误。
然而,令我惊讶的是,同样的错误发生了:
The operation cannot be completed because the DbContext has been disposed
我很惊讶这种延迟加载真的很懒并且只在最后一刻加载。
所以我继续我的'wrong'假设如下:
5-可能我需要强制 View() 方法在 using 语句内执行结果。所以我用了这个方法ExecuteResult(ControllerContext)
.
现在我想我可以运行操作方法而不会出现任何错误
但同样的错误又发生了:
The operation cannot be completed because the DbContext has been disposed.
所以我现在的问题是:
MVC 框架中的哪个位置执行延迟加载查询?
或者让我将我的问题改写如下:
Why did View(d)
当 [d] 对象位于 using 语句之外时,方法会迭代该对象,而当 view(d) 方法位于 using 语句内部时,则不会迭代该对象。
我只需要了解为什么我的假设是错误的..
提前致谢