在页面加载时处理的模型绑定DBContext

本文关键字:模型 绑定 DBContext 处理 加载 | 更新日期: 2023-09-27 18:09:42

我一直在努力理解为什么当我添加。skip()和。take () linq方法到查询时,我会得到DBContext处置错误。我有一个运行良好的版本,它没有上面提到的方法,只是无法理解是什么造成了差异。

这是两个方法,返回数据到一个模型绑定GridView的选择方法:

// This is the method that causes the DBContext disposed exception
            public IQueryable<ProductCategory> GetCategoriesByPage(int pageNumber, int pageSize)
        {
            using (var dataModel = new MagicDayEntities())
            {
                var pagedCategories = (from categories in dataModel.ProductCategories
                                       orderby categories.CategoryName ascending
                                       select categories)
                        .Skip((pageSize - 1) * pageNumber)
                        .Take(pageSize);
                pagedCategories.ToList().AsQueryable();
                return pagedCategories;
            }
        }
//This method returns the data properly without error
        public IQueryable<ProductCategory> GetAllCategories()
        {
            using (var dataModel = new MagicDayEntities())
            {
                var allCategories = (from categories in dataModel.ProductCategories
                                     orderby categories.CategoryName ascending
                                     select categories)
                                     .ToList()
                                     .AsQueryable();
                return allCategories;
            }
        }

据我所知,ToList()应该强制运行查询,并克服延迟加载行为,并使DbContext处于"using"语句中,这是必需的。

下面是异常的详细信息:

The operation cannot be completed because the DbContext has been disposed. 
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.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
Source Error: 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 
Stack Trace: 

[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +4249201
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +40
   System.Linq.Queryable.Count(IQueryable`1 source) +196
   System.Web.UI.WebControls.QueryableHelpers.CountHelper(IQueryable`1 queryable) +48
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   System.Web.UI.WebControls.ModelDataSourceView.ProcessSelectMethodResult(DataSourceSelectArguments arguments, DataSourceSelectResultProcessingOptions selectResultProcessingOptions, ModelDataMethodResult result) +249
   System.Web.UI.WebControls.ModelDataSourceView.GetSelectMethodResult(DataSourceSelectArguments arguments) +92
   System.Web.UI.WebControls.ModelDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +15
   System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +22
   System.Web.UI.WebControls.ModelDataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +80
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +143
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +74
   System.Web.UI.WebControls.GridView.DataBind() +9
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +114
   System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +75
   System.Web.UI.Control.EnsureChildControls() +92
   System.Web.UI.Control.PreRenderRecursiveInternal() +42
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +883

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1586.0 

有没有人能帮我一下,并解释一下这个异常的原因?提前感谢。彼得。

在页面加载时处理的模型绑定DBContext

通过调用ToList:

执行查询
pagedCategories.ToList().AsQueryable();

然后忽略结果并返回原始查询,该查询将在视图绑定到它时执行:

return pagedCategories;

更改为返回列表:

return pagedCategories.ToList().AsQueryable();

我还建议将返回类型更改为IEnumerable<ProductCategory>并删除对AsQueryable的调用。这样做没有任何意义