ObjectDisposedException While using Include

Total Post:128

 1176  View(s)
Rate this:

My page calls a Services layer method that uses a Generic Repository "Find" method. In the services layer method, I do the following:

 using (IUnitOfWork unitOfWork = new DBContext())
                    GenericRepository<Operator> operatorRepos = new GenericRepository<Operator>(unitOfWork);
                            var oper = operatorRepos.Find(o => o.OperatorID ==operatorID).Include(o => o.cmn_Address).Single();
                            return oper;
                        catch (InvalidOperationException exc)
                            //handle exception

The Find method for my repository:

public IQueryable<T> Find(Func<T, bool> predicate)
            return _objectSet.Where<T>(predicate).AsQueryable();

On the page, I try to access the cmn_address Navigation property of the Operator and I get the following error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I realize that this is caused by the using statement to dispose of the context, but I thought the Include method will eager load the cmn_Address object. I don't understand why this doesn't work as I expected.

  1. Post:378

    Re: ObjectDisposedException While using Include

    Hi Ashish, 

    You are using Func<> instead of Expression<Func<>> in your where condition. That makes it Linq-to-objects. This change is permanent. Calling AsQueryable doesn't make it Linq-to-entities again.



Enter your email address here always to be updated. We promise not to spam!