i was trying to write a full detailed answer to the following question: Why does "Dispose" work, and not "using(var db = new DataContext())"?
so I set up my project that include:
Departments and employees using entity framework
so my action method was this:
public ActionResult Index()
{
IEnumerable<department> d;
using (var ctx = new ApplicationDbContext())
{
d = ctx.departments;
}
return View(d);
}
it is natural to expect that this will result in the common error :
The operation cannot be completed because the DbContext has been disposed
and when i wanted to resolve it I did the following [to force eager loading rather than easy loading] :
public ActionResult Index()
{
IEnumerable<department> d;
using (var ctx = new ApplicationDbContext())
{
d = ctx.departments.toList();
}
return View(d);
}
so I was trying to understand things under the hood and looked at the return type of the View() method. and I reached to the following 'Correct' assumptions:
1- the model [d] is called in lazy loading fashion inside the using statement.
2- so when the model [d] is sent to the view for generating the page the DbContext is already disposed by the last curly bracket of the using statement.
3- we solve this situation by sending the model [d] to the view with eager loading fashion.
then I continued my assumptions that proved to be 'wrong' as following:
4- since the View() method is returning ViewResult object which is an ActionResult also..then I can generate this object inside the using statement and then return it to the user.
so I did the following:
public ActionResult Index()
{
ActionResult myView;
using (var ctx = new ApplicationDbContext())
{
IEnumerable<department> d = ctx.departments;
myView = View(d);
}
return myView;
}
so I told myself now when I run it , the ViewResult object [ myView] will be already created and will be returned to the user and No Error will be encountered.
However I was surprised that the same error occured :
The operation cannot be completed because the DbContext has been disposed
I was astonished how this lazy loading is really lazy and load only at the last moment.
So I continued my 'wrong' assumptions as follow:
5- may be I need to force the View() method to excute the result inside the using statement. so I used the method ExecuteResult(ControllerContext)
.
and now I thought I can run the action method without any error but again the same error occured:
The operation cannot be completed because the DbContext has been disposed.
So my question now is:
where in the MVC framework does the excution of lazy loading query occur !!
or let me rephrase my question as follow:
Why did View(d)
method iterate over the [d] object when it is out of the using statment, and not when the view(d) method is inside the using Statement.
I just need to understand why my assumptions were wrong .. Thanx in advanced