Pavel Voronin
Pavel Voronin

Reputation: 13993

How to detach an object graph from object context in Entity Framework without roundtrips to database?

The workflow of my app is quite simple:

For a given bunch of scripts

  1. take a script
  2. parse it
  3. get corresponding object graph from db
  4. update it or create new if no graph found
  5. save changes
  6. detach graph from object context for GC could kill the graph

The last item of the list is not necessary if object context is created for each script but it affects performance, moreover I want some of the entities stored in the context whereas others collected by GC.

I thought of manually detaching entities:

foreach (var desc in component.Descriptions)
   context.ComponentDescription.Detach(desc);
context.Components.Detach(component);

Such enumeration implies db querying in case of enabled lazy loading. It's not a good thing at all.

I found such a way more like a hack:

var entities = context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged).Where(
                        e => !(e.Entity is ComponentType));
entities.Iterate(e => e.ChangeState(EntityState.Detached));

Well, it's not a graph detaching, but I just know I can do this in my case. But what if I need to work with the certain graph, how can I detach related properties without 'disturbing' db?

Upvotes: 2

Views: 797

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364319

As I your question the problem is call to component.Descriptions because it triggers lazy loading if descriptions are not loaded. So the solution should be easy. Temporary disable lazy loading during this operation.

context.ContextOptions.LazyLoadingEnabled = false;

foreach (var desc in component.Descriptions)
   context.ComponentDescription.Detach(desc);
context.Components.Detach(component);

context.ContextOptions.LazyLoadingEnabled = true;

I don't understand why do you thing that creating context for each operation affects performance. The reverse is usually true - reusing context affects performance.

Upvotes: 2

Related Questions