从会话变量访问数据时获取ObjectContext Disposed异常

时间:2014-11-14 17:27:21

标签: asp.net-mvc entity-framework

我现在已经多次尝试过这个问题了,要么没有人知道答案,要么他们认为之前已经回答过。我还没有找到答案,所以我不认为它有。

使用MVC5 EF6。

我有一个针对存储库运行的搜索。在离开Controller之前,我放置搜索结果(使用ToList()以确保枚举结果)。然后我返回视图传递结果。这很好用。

[AllowAnonymous]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public async Task<ActionResult> SearchDispensaries(DispensarySearchModel model,
    int pageNumber = 1, int pageSize = 10, string sortByField = "Dba", bool sortAscending = true) {
    IEnumerable<Dispensary> found = null;
    if ((model == null || !model.NewSearch) && Session["DispensariesFound"] != null) {
        found = Session["DispensariesFound"] as List<Dispensary>;
    }
    if(ModelState.IsValid) {
        found = await _dispensaries.SearchAsync(model, sortByField, sortAscending);
        Session["DispensariesFound"] = found;
    }
    ViewBag.PageNumber = pageNumber;
    ViewBag.PageSize = pageSize;
    ViewBag.SortByField = sortByField;
    ViewBag.SortAscending = sortAscending;
    ViewBag.SortingEnabled = true;
    if (Request.IsAjaxRequest()) {
        return PartialView("_Dispensaries", found);
    }

    return View("DispensarySearchResults", found);
}

在视图中,我可以更改页面或排序规则。我还有另外一个功能......

        [AllowAnonymous]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult SortAndPageDispensaries(int pageNumber = 1, int pageSize = 10, string sortByField = "Dba",
        bool sortAscending = true) {
        var found = (Session["DispensariesFound"] as IEnumerable<Dispensary>) ?? new List<Dispensary>();
        found = _dispensaries.ApplySort(found, sortByField, sortAscending).ToList();
        ViewBag.PageNumber = pageNumber;
        ViewBag.PageSize = pageSize;
        ViewBag.SortByField = sortByField;
        ViewBag.SortAscending = sortAscending;
        ViewBag.SortingEnabled = true;
        if (Request.IsAjaxRequest()) {
            return PartialView("_Dispensaries", found);
        }

        return View("DispensarySearchResults", found);
    }

在返回行放置一个断点我可以看到结果是枚举的。此函数中没有涉及或引用任何DbContext。但是在_Dispensaries视图中我收到了错误

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Source Error: 



Line 38:                <tr class="table-row">
Line 39:                    <td class="item-followers text-center">
Line 40:                        @item.FavoritedBy.Count
Line 41:                    </td>
Line 42:                    <td colspan="1" class="text-center">


 Source File:  d:\Projects\Web\Fhlora\Fhlora\Views\Shared\_Dispensaries.cshtml    Line:  40 

我有几个类似的页面搜索其他实体类型,这种方法适用于所有这些类型。有谁知道我可能做错了什么?我已经尝试了所有我知道的事情。

1 个答案:

答案 0 :(得分:0)

当您启用了延迟加载时,存储在Session中的对象将连接到ObjectContext,这样当您对表运行查询时,只有在您访问它时才会填充FavoritedBy引用。

在对象上下文中启用预先加载或者急切加载FavoritedBy引用。

你可以在你的门诊服务中用EF with Include()方法做到这一点:

var q = Dispensaries.Include(i => FavoritedBy).Sort(..);