Open Closed

Because the DbContext has been disposed. #238


0
sayram created

I have a CategoryService I'm using a method like below

public IEnumerable<Category> GetCategories(ContentState state)
        {
            var categories = _categoryRepository.GetAll().Where(c => c.CategoryState == state.ToString());

            //var categories = _categoryRepository.GetAllList(c => c.CategoryState == state.ToString());
            return categories;
        }

this is the AddCategory method in controller

public ActionResult AddCategory()
        {
            var categories = _categoryService.GetCategories(ContentState.Published);
            var viewModel = new CreateCategoryViewModel
            {
                Categories = categories.ToSelectListItems(-1),
            };

            return View(viewModel);
        }

Btw this is the ContentState

public enum ContentState
    {
        Published,
        Unpublished,
        Trashed,
        Pending
    }

and thi is the Category entity

public partial class Category : Entity
    {
        public Category()
        {
            this.SubCategories = new List<Category>();
            this.Videos = new List<Video>();
        }

        public int? ParentId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string MetaKeys { get; set; }
        public string MetaDescription { get; set; }
        public string CategoryState { get; set; }
        public virtual ICollection<Category> SubCategories { get; set; }
        public virtual Category ParentCategory { get; set; }
    }

Viewmodel

public class CreateCategoryViewModel 
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string MetaKeys { get; set; }
        public string MetaDescription { get; set; }
        public string CategoryState { get; set; }
        public string Button { get; set; }
        //public string ActionMessage { get; set; }

        public IEnumerable<SelectListItem> Categories { get; set; }

    }

this is the where i get the error

@helper PrintCategories(dynamic categories)
{
    foreach (var item in categories)
    {
        @item.Title
        <br />
        var subCategories = item.SubCategories;
        if (subCategories != null && subCategories.Count > 0)
        {
            PrintCategories(subCategories);
        }
    }
}
                            <div class="form-group">
                                <div class="col-lg-10">
                                    @PrintCategories(Model.Categories)
                                </div>
                            </div>

so when im trying to access navigation property i get this error

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.

Stack Trace

[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +762
   System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +28
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator() +52
   ASP.<>c__DisplayClassd.<PrintCategories>b__c(TextWriter __razor_helper_writer) in c:\Users\saYRam\Documents\Visual Studio 2013\Projects\Index Projects\Index.Web\Areas\Administrator\Views\Category\AddCategory.cshtml:82
   System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10
   System.Web.WebPages.WebPageBase.Write(HelperResult result) +80
   ASP._Page_Areas_Administrator_Views_Category_AddCategory_cshtml.Execute() in c:\Users\saYRam\Documents\Visual Studio 2013\Projects\Index Projects\Index.Web\Areas\Administrator\Views\Category\AddCategory.cshtml:71
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2b.&lt;BeginInvokeAction&gt;b__1c() +173
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.&lt;BeginExecute&gt;b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9723757
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I think its related Lazy Loading which is i realy scared when i hear its name. I have no idea how can i get rid of this.


7 Answer(s)
  • 0
    hikalkan created
    Support Team

    You can not return IQueryable from application service method. Just use ToList() after Where condition.

  • 0
    sayram created

    <cite>hikalkan: </cite> You can not return IQueryable from application service method. Just use ToList() after Where condition.

    changed code below

    ...
                var categories = _categoryRepository.GetAll().Where(c => c.CategoryState == state.ToString());
    ...
    

    to

    ...
                var categories = _categoryRepository.GetAll().Where(c => c.CategoryState == state.ToString()).ToList();
    ...
    

    This time a get this error.

    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.
    

    This is the Stack trace

    [ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.]
       System.Data.Entity.Core.Objects.ObjectContext.get_Connection() +91
       System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +273
       System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption) +83
       System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption) +203
       System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption) +51
       System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load() +59
       System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad() +438
       System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +165
       System.Data.Entity.Core.Objects.Internal.<>c__DisplayClass7`2.&lt;GetInterceptorDelegate&gt;b__1(TProxy proxy, TItem item) +205
       System.Data.Entity.DynamicProxies.Category_93B8F10007F4823D6C15308F82C291EDF6CC0E4BAC3D32B099E0561F771A5140.get_SubCategories() +75
       CallSite.Target(Closure , CallSite , Object ) +189
       System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) +517
       ASP.&lt;&gt;c__DisplayClassd.&lt;PrintCategories&gt;b__c(TextWriter __razor_helper_writer) in c:\Users\saYRam\Documents\Visual Studio 2013\Projects\Index Projects\Index.Web\Areas\Administrator\Views\Category\AddCategory.cshtml:82
       System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +42
       System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +45
       System.Web.WebPages.WebPageBase.Write(HelperResult result) +53
       ASP._Page_Areas_Administrator_Views_Category_AddCategory_cshtml.Execute() in c:\Users\saYRam\Documents\Visual Studio 2013\Projects\Index Projects\Index.Web\Areas\Administrator\Views\Category\AddCategory.cshtml:91
       System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +270
       System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +122
       System.Web.WebPages.StartPage.RunPage() +63
       System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
       System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
       System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
       System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
       System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
       System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
       System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
       System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
       System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
       System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9723757
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
    

    i really did not understood why and where i made mistake.

  • 0
    hikalkan created
    Support Team

    I believe that you willl understand it if you check <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work">http://www.aspnetboilerplate.com/Pages/ ... it-Of-Work</a> document.

    If you're using your app service directly (without an interface), your method should be virtual. Also, service should implement IApplicationService.. etc. Please read document carefully since you may get same exception in different situations without understanding the reason completely. Especially here: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work#DocRepositoryGetAll">http://www.aspnetboilerplate.com/Pages/ ... toryGetAll</a>

  • 0
    omar created

    I am having the same issue when using AbpApiController.

    public class UsersController : AbpApiController
        {
            private readonly IRepository<User, long> _userRepo;
          
            public UsersController(  IRepository<User,long> userRepo)
            {     
                _userRepo = userRepo;
            }
    
            [HttpGet]
            [UnitOfWork]
            public virtual dynamic GetAll()
            {
               return _userRepo.GetAllList();
            } 
        }
    
  • 0
    hikalkan created
    Support Team

    You should not return Entity to the client, instead use DTO. Why? See DTO document: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Data-Transfer-Objects">http://www.aspnetboilerplate.com/Pages/ ... er-Objects</a> (especially, Serialization & lazy load problems section)

  • 0
    paddyfink created

    Hey there, I'm having the same issue in a mvc controller.

    public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
            {
                var suppliers = GetAll();
    
                return Json(suppliers.ToDataSourceResult(request));
            }
    
            [UnitOfWork]
            public virtual IEnumerable<SupplierListOutput> GetAll()
            {
               return _supplierRepository.GetAll().ProjectTo<SupplierListOutput>();
            }
    

    I'm using kendo ui Grid component that can performs filtering, sorting, paging.... That's why I need to have a direct acces to the repository in my controller and pass a IQueryable variable in my action method .

    But I stilll have the error : The operation cannot be completed because the DbContext has been disposed.

    The repository is injected in the controller constructor

  • 0
    hikalkan created
    Support Team

    Hi,

    You can not return IQueryable from a Controller since database connection is closed after your method. Then KendoUI fetches quest while connection is closed.

    If you really need to return IQueryable, then you should manage connection yourself. How? I did similar thing in odata sample. I started UOW manually (<a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Zero/Edition-Management">http://www.aspnetboilerplate.com/Pages/ ... Management</a>) and finished manually (<a class="postlink" href="https://github.com/aspnetboilerplate/sample-odata/blob/master/src/AbpODataDemo.WebApi/Controllers/AbpODataEntityController.cs#L122">https://github.com/aspnetboilerplate/sa ... er.cs#L122</a>). You can implement similar thing for you.