Home > DeveloperSection > Forums > ObjectDisposedException While using Include
Ashish Pandey

Total Post:128

Points:898
Posted on    August-29-2014 1:14 AM

 C#
Ratings:


 1 Reply(s)
 663  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);

                    {

                        try

                        {

                            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.



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    September-01-2014 12:20 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick