@foreach (Thing thing in Model) {
@Html.Action("someAction", "someOtherController", thing)
//kind of a PartialView but coming from another controller
}
-
public class someOtherController: Controller
{
public PartialViewResult someAction(Thing Model)
{
...
}
When this Html.Action is getting called I get The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
This is an error I'm usually able to fix using .Include()
in the appropriate place in the code.
But in this case:
@Html.Action("someAction", "someOtherController", thing)
but if I put a breakpoint on the first line of someAction(...)
method, it is never reached.@Html.Action("someAction", "someOtherController", thing)
instead of calling it through the partial view, it works perfectly. - So there must be something wrong between that call and the controller, but I can't point out what. Any idea how I could debug this further and/or solve the problem?
Somebody asked for the query:
Data access layer :
public static List<Thing> GetAllThings(string[] Include = null)
{
using (Entities ctx = new Entities())
{
if ((Include != null) && (Include.Length > 0))
{
System.Data.Entity.DbSet<Thing> things= ctx.Things;
System.Data.Entity.Infrastructure.DbQuery<Thing> thingQuery= things.Include(Include[0]);
for (int i = 1, c = Include.Length; i < c; i++)
thingQuery= thingQuery.Include(Include[i]);
return thingQuery.ToList();
}
return ctx.Things.ToList();
}
}
In controller:
public ActionResult Index()
{
string[] include = new string[] { "Stuff1.Stuff2", "Stuff4.Stuff5.Stuff6", "Stuff7.Stuff8" };
List<Things> things = ThingsManager.GetAllThings(include).OrderBy(x => x.Name).ToList();
return this.View(things);
}
The exception message explains it all: your database context is falling out of scope before something is trying to enumerate a lazy-loaded related entity.
Check to make sure that you are eager-loading all your related entities that this block of code operates on:
@foreach (item dto in items) {
@Html.Action("someAction", "someOtherController", item) //kind of PartialView but coming from another controller