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. ..
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 createlist
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 theAddress
property. Since this is not loaded yet, EF will attempt to query the database using the parentObjectContext
of the entities inlist
. 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 loadlist
.Change your original query to look like the following: