Entity Framework - restoring navigation property after detaching entities

999 Views Asked by At

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.

2

There are 2 best solutions below

1
Jan Muncinsky On BEST ANSWER

You can use LoadProperty method:

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

0
Sonikas On

to detach entities just use AsNoTracking

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .AsNoTracking()
        .ToList();
}

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