I have found myself explaining this in conference sessions so I thought I would write it down in my blog.
Entity Framework has a Golden Rule. Though shalt not do nuttin’ that the developer has not explicitly told you to do. The lack of implicit lazy loading is one of the more notable (and hotly contested by some) example of this.
But one day when I was coding, Entity Framework did something that I did not ask it to do. I emailed Danny Simmons to tattle on the API. But Danny explained something to me about RelationshipSpan that needs to override the Golden Rule.
I now call it the Platinum Rule. (I learned this pecking order from American Express).
The Platinum Rule is that an object graph (for example when a customer is attached to an order which is attached to some line items) must be completely in or completely outside of the ObjectContext.
The way I discovered it was that I had a Customer that was being change tracked by an ObjectContext.
I created a new order and attached the order to the customer.
But I did NOT add or attach the order to the context.
Yet, the order was suddenly within the context and being change tracked. Why? Because of the Platinum rule. By attaching the order to the customer, I was creating a graph. Since the graph can’t have some of its objects in the context and some of its objects out of the context, it has three options.
- Don’t allow the objects to be connected. (Now wouldn’t that tick you off?)
- Pull the customer out of the context. (Now wouldn’t that really tick you off?)
- Pull the order INTO the context.
Okay, works for me.
So this is the same rule that confuses people when they have an object graph that is IN the context and they detach one of its objects. That object leaves the context and “broken”off of the graph. So if you called context.Detach(Customer), then the customer is detached but the Order and its Line Items are still in the context.
You can no longer traverse from the Customer to the Order or from the Order to the Customer.
On the flip side, if you have an object graph that is not being change tracked – the whole package, Customer, the order and the details and they are all attached to one another, if you attach any one of them to the context, the whole kit n’ caboodle gets pulled into the context – because of the platinum rule.
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!