ObjectContext is disposed, can not longer used

58 views Asked by At

Example Code:

private static list;
public void SetList ()
{
var query = Container.Advices.Where ();
list= query.ToList();
}

public void doStuff ()
{
var temp= list.where (...).ToList ();
}

problem situation:

When i call the first time SetList, all worked fine. Now, a second is SetList called. I can see in the method, there are all objects, but in the second method doStuff is an exception thrown: ObjectContext is disposed ... I'm not understanding why. I saw the data is loaded correctly in the list and not a second later i can ' t load the navigation properties.

How can i fix this?

EDIT

What i do: 1. I call SetList() to initialize the list First time 2. doStuff all worked fine 3. I recreate the list with SetList 4. Next call to doStuff ended in exception on the try to use navigation properties:

var temp = list.where ( m=> m.Address.id==addressId).ToList ()

Failed on the second time with exception: ObjectContext is disposed. ..

1

There are 1 answers

0
mclark1129 On BEST ANSWER

The problem is likely that by default Navigation Properties are lazy-loaded. This means that they're not actually returned by the database until you attempt to access them. The ObjectContext that you are using to create list is being disposed somewhere, and that's a good thing because you do not what the lifetime of your context to be too long.

The reason that your next call errors on list.where(m => m.Address.id == addressId).ToList() is because you are going to iterate over the list and access the Address property. Since this is not loaded yet, EF will attempt to query the database using the parent ObjectContext of the entities in list. Since the parent context is disposed, this is not possible.

The better and likely more performant way to accomplish this would be to eagerly load the Address property when you load list.

Change your original query to look like the following:

list = queryContainer.Advices
    .Where(m => /* Some Predicate */)
    .Include(m => m.Address).ToList();