Solving “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection” InvalidOperationException

前端 未结 7 2211
再見小時候
再見小時候 2020-11-22 06:38

I am trying to populate a GridView using Entity Frameworkm but every time I am getting the following error:

\"Property accessor \'LoanPro

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:51

    Most of the other answers point to eager loading, but I found another solution.

    In my case I had an EF object InventoryItem with a collection of InvActivity child objects.

    class InventoryItem {
    ...
       // EF code first declaration of a cross table relationship
       public virtual List ItemsActivity { get; set; }
    
       public GetLatestActivity()
       {
           return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
       }
    ...
    }
    

    And since I was pulling from the child object collection instead of a context query (with IQueryable), the Include() function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity() and attach() the returned object:

    using (DBContext ctx = new DBContext())
    {
        var latestAct = _item.GetLatestActivity();
    
        // attach the Entity object back to a usable database context
        ctx.InventoryActivity.Attach(latestAct);
    
        // your code that would make use of the latestAct's lazy loading
        // ie   latestAct.lazyLoadedChild.name = "foo";
    }
    

    Thus you aren't stuck with eager loading.

提交回复
热议问题