【发布时间】:2014-01-30 16:00:54
【问题描述】:
@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);
}
【问题讨论】:
-
ObjectContext在哪里被打开和关闭?
-
当它在调试中工作时,您的 ObjectContext 似乎是静态的。这是一种不好的做法。
-
您需要提供更多信息才能获得答案。填充“items”的查询是什么,“someOtherController”中的“someAction”对“item”有什么作用?通常,您是正确的,因为您应该能够使用急切加载的“包含”语句来解决此问题。确认您正在加载所有将被枚举的相关实体。
-
@ivowiblo: 在主视图的控制器中
-
@ivowiblo:不,它不是静态的
标签: c# asp.net-mvc partial-views objectdisposedexception