If you have a graph of entities which are being managed by an ObjectContext, e.g, a LineItem and its Product, and for one reason or another, you detach the Product from the context, lazy loading will query for that Product again if you happen to call LineItem.Product. Now you will have two instances of that product in memory and one of them is being change-tracked.
It’s understandable behavior, but I know that someone will get bitten by this someday.
It’s more likely to happen when you are exploring how relationships work and doing weird things like I do. But it’s also possible that you might do it in a production app as well if you don’t know what you’re doing.
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!
2 thoughts on “Entity Framework Graphs, Detaching and Lazy Loading”
I have been struggling with detaching object graph. I have a parent and children scenario. When I detach the Parent then the children are not detached. Therefore, the Parent.MyChildren property will be zero outside of that context. So I tried, removing the children and then the parent. Still no luck. How can I detach the entire object graph so the end user can work with the entire object graph in one single call?
you have to detach all of hte children first, then detach the parent but then they won’t be an in-memory grapy any more. You’d have to rebild graph in memory. It’s a completely sucky scenario. Tae a looke at gotcha #5 somewhat related…