“ObjectContext已被处理”/多控制器视图

时间:2014-01-30 16:00:54

标签: c# asp.net-mvc partial-views objectdisposedexception

@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)
    {
        ...
    }

当调用此Html.Action时,我得到The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

这是我通常可以使用.Include()在代码中的适当位置修复的错误。

但在这种情况下:

  • 在调试时,它看起来不像“东西”或已包含的子实体已被处置。
  • 我可以在@Html.Action("someAction", "someOtherController", thing)上设置一个断点,但是如果我在someAction(...)方法的第一行放置一个断点,它就永远不会到达。
  • 我有另一个页面使用这种局部视图,它完美地运作
  • 如果我在@Html.Action("someAction", "someOtherController", thing)的位置生成内容而不是通过局部视图调用它,则效果很好。 -

所以那个电话和控制器之间肯定有问题,但是我不能指出是什么。知道如何进一步调试和/或解决问题吗?


有人要求查询:

数据访问层:

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();
    }
}

在控制器中:

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);
}

1 个答案:

答案 0 :(得分:2)

异常消息解释了这一切:在尝试枚举延迟加载的相关实体之前,您的数据库上下文超出了范围。

检查以确保您急切加载此代码块操作的所有相关实体:

@foreach (item dto in items) {
    @Html.Action("someAction", "someOtherController", item) //kind of PartialView but coming from another controller