The workflow of my app is quite simple:
For a given bunch of scripts
- take a script
- parse it
- get corresponding object graph from db
- update it or create new if no graph found
- save changes
- 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?
As I your question the problem is call to
component.Descriptionsbecause it triggers lazy loading if descriptions are not loaded. So the solution should be easy. Temporary disable lazy loading during this operation.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.