【发布时间】:2014-06-16 23:59:04
【问题描述】:
我试图为以下问题写一个完整的详细答案: Why does "Dispose" work, and not "using(var 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() 方法的返回类型。我得出了以下“正确”假设:
1- 在 using 语句中以延迟加载方式调用模型 [d]。
2- 所以当模型 [d] 被发送到视图以生成页面时,DbContext 已经被 using 语句的最后一个花括号处理了。
3- 我们通过将模型 [d] 以预加载方式发送到视图来解决这种情况。
然后我继续我的假设被证明是“错误”如下:
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
我很惊讶这种延迟加载真的很懒,而且只在最后一刻加载。
所以我继续我的“错误”假设如下:
5- 可能我需要强制 View() 方法在 using 语句中执行结果。所以我使用了ExecuteResult(ControllerContext)的方法。
现在我认为我可以运行操作方法而不会出现任何错误 但同样的错误又发生了:
The operation cannot be completed because the DbContext has been disposed.
所以我现在的问题是:
延迟加载查询的执行在MVC框架的什么地方发生!!
或者让我把我的问题改写如下:
为什么 View(d) 方法在 [d] 对象不在 using 语句时迭代它,而不是在 view(d) 方法在 using 语句内时迭代。
我只需要了解为什么我的假设是错误的.. 先进的thanx
【问题讨论】:
标签: c# asp.net-mvc entity-framework lazy-loading