Entity Framework Graphs, Detaching and Lazy Loading

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

  1. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.