" DataContext的处置&QUOT后访问;从ActionResult的方法处理的控制器时的DataContext错误ASP.NET MVC 3 [英] "DataContext accessed after Dispose" error when disposing datacontext from ActionResult method in controller ASP.NET MVC 3

查看:123
本文介绍了" DataContext的处置&QUOT后访问;从ActionResult的方法处理的控制器时的DataContext错误ASP.NET MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code:

public ActionResult MainMenu(int id)
{
  using (WebDataContext context = new WebDataContext())
  {
    //var dataLoadOptions = new System.Data.Linq.DataLoadOptions();
    //dataLoadOptions.LoadWith<MenuCache>(x => x.Menu);
    //context.LoadOptions = dataLoadOptions;

    var menu = context.MenuCaches
                      .AsEnumerable()
                      .Where(x => x.ID == id 
                                  && (x.Local == true || x.National == true));
    foreach (var item in menu)
    {
      if (item.Parent.Parent != null && item.Parent.ParentID == 0)
      {
        menu = item.Children;
      }
    }
    return View(menu.ToList());
  }
}

我发现了一些选项在线上如何​​解决它。一个是做收益回报视图(菜单)); 但给我的的ActionResult不是一个迭代的误差 。在功能上的评论code是另一种选择,我发现,但是这也不能工作。有任何想法吗?非常感谢。

I found some options online on how to fix it. One was to do yield return View(menu)); but that gave me the error that ActionResult is not an iterator. The commented code in the function was another option that I found, but that didn't work either. Any ideas? Thanks a lot.

推荐答案

我不能肯定,但它可能是与该返回查看(menu​​.ToList()),因为我相信实际的结果(视图)不直到后来在MVC管线执行的,所以在了ToList()不是之后才执行你的 WebDataContext 配置。我敢打赌,这样就解决了问题:

I can't be certain, but it's probably something to do with the return View(menu.ToList()) as I believe the actual result(the view) isn't executed until later in the MVC Pipe line, so the ToList() isn't executed until after your WebDataContext is disposed. I bet this would resolve the issue:

public ActionResult MainMenu(int id)
{
  IENumerable<MenuCache> menu;

  using (WebDataContext context = new WebDataContext())
  {
    menu = context.MenuCaches
                  .AsEnumerable()
                  .Where(x => x.ID == id 
                              && (x.Local == true || x.National == true));

    foreach (var item in menu)
    {
      if (item.Parent.Parent != null && item.Parent.ParentID == 0)
      {
        menu = item.Children;
      }
    }
    menu = menu.ToList();
  }
  return View(menu);
}

这篇关于&QUOT; DataContext的处置&QUOT后访问;从ActionResult的方法处理的控制器时的DataContext错误ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆