Entity Framework - restoring navigation property after detaching entities

.net entity-framework entity-framework-6 lazy-loading objectcontext


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:


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.

11/14/2017 2:50:44 PM

Accepted Answer

You can use LoadProperty method:

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

11/11/2017 9:45:27 AM

Popular Answer

to detach entities just use AsNoTracking

using (var context = new BloggingContext())
    var blogs = context.Blogs

if you want entity framework again to track changes you need Attach it to context and use ctx.myDbSet.Include(x=>x.Something)

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow