How to prevent lazy loading of entities that were already manually loaded when navigating a property in EntityFramework

StackOverflow https://stackoverflow.com/questions/14939788

Question

Background: I am using EF4 and ObjectContext. To optimze retrieval of complex object hierarchies, I manually execute database queries and then use ObjectContext.Translatey<T>(DataReader, entitySetName, mergeOptions.AppendOnly) to turn data rows into entities. I then attach the entities to the ObjectContext with Attach method. This also fixes relations between entities.

The problem: After everything is loaded and set up I try to navigate from parent entity to a child entity (for example Parent.Childs.First()), but EF hits the database to load the kids, even though all the child entities are already present in the ObjectContext and EntitySet. It looks like the reason for this is that parent.Childs.IsLoaded is set to false which makes EF think that it still needs to load the relation.

Question: How can I tell EF that EntitySet has already been loaded?

Is there a supported way to set RelatedEnd.IsLoaded to true. I wouldn't like to mess with the calling the RelatedEnd.SetIsLoaded internal method.

I found a smilar question here but it relates to DbContext and has no satifying answer ;-)

Matra

Was it helpful?

Solution

It looks like this was implemented in this change: http://entityframework.codeplex.com/workitem/269

You can now iterate through your entities and tell them that their child collections are already loaded:

foreach (var entity in loadedEntities)
  context.Entry(entity).Collection(a => a.SomeChildCollection).IsLoaded = true;

This will prevent entities in SomeChildCollection from being loaded when they are accessed from entity.

I'm not exactly sure what version of EF this appeared in but I'm guessing 6.0.0.

OTHER TIPS

The only way to solve this is to turn off lazy loading. The question you have found on MSDN asks about DbContext but the answer mentions that there is no way to change the value in underlying libraries - ObjectContext API (= EF4 in your case) is the underlying library. Even in .NET 4.5 (EF5) setting IsLoaded is still not available on public API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top