.netentity-frameworkentity-framework-6lazy-loadingobjectcontext

Entity Framework - restoring navigation property after detaching entities


My Entity Framework model (using EF 6.1 with ObjectContext), has lazy loading turned on, with various navigation properties.

For example:

// Orders is a navigation property (collection), which, when first iterated,
// loads the collection of Order entities from the DB
var orders = Customer.Orders.ToList();

In my app, for performance reasons, I want to be able to detach Order entities and allow them to be garbage collected:

MyContext.Detach(order1);
MyContext.Detach(order2);
MyContext.Detach(order3);

But, I have found that when I detach only a subset of the child entities (i.e. not all of them), the next iteration of Customer.Orders does not work – the detached entities are not part of the returned collection.

What code can I write to get the Customer.Orders navigation property to restore and work correctly in this situation, forcing it to reload and re-attach all entities, including those previously detached?

I have tried manually setting Customer.Orders.IsLoaded to false, but that doesn't work - the entities are not re-loaded, and somewhere under the EF hood IsLoaded simply gets set back to true.


Solution

  • You can use LoadProperty method:

    context.LoadProperty(customer, c => c.Orders, MergeOption.OverwriteChanges);