Repository navigation
Description
In EF6.x the default behavior of these methods was to start tracking every reachable entity in the state being requested for the root entity. This caused a lot of issues because:
- Attaching a root would often end in exceptions because there were new entities in the graph (with no PK set) which would attempt to be tracked as unchanged, resulting in duplicate PK values.
- There was no easy mechanism to traverse over a graph and chose the state of each entity as you go.
- There was no ability to leave parts of the graph un-tracked (i.e. I want to add an order and I don't care about telling you the state of the Customer).
In EF Core we tried to alleviate some of these issues by initially making Add/Attach/etc. just work on a single object, but this caused a lot of confusion since it seems the natural expectation (based on the feedback we saw) is that you could add an Order and the OrderLines would be automatically added too.
We then tried an "Include Dependents" approach, where if you add a parent, we also include the children as added. This works well for some cases... but it gets pretty confusing. This is compounded by the fact that it's not always clear from your model which is the principal/dependent of a relationship.
After discussion, we realized that with some small variations on the rules from EF6.x, we already have APIs in EF Core to enable these scenarios:
There was no easy mechanism to traverse over a graph and chose the state of each entity as you go.
We have the TrackGraph API for exactly this purpose.
There was no ability to leave parts of the graph un-tracked (i.e. I want to add an order and I don't care about telling you the state of the Customer).
This is now supported in EF Core, our stack is capable of handling entities in the graph that it is not tracking. We have the DbContext.Entry(...).State API that allows you to put a single entity into the context without any graph behavior (i.e. no related entities are brought in).
Attaching a root would often end in exceptions because there were new entities in the graph (with no PK set) which would attempt to be tracked as unchanged, resulting in duplicate PK values.
We will adjust the graph behavior of these APIs as follows:
Add: Adds every reachable entity that is not already trackedAttach: Attaches every reachable entity, except where a reachable entity has a store generated key and no key value is assigned, these will be marked as added.Update: Same asAttach, but entities are marked as modifiedRemove: Same asAttach, and then mark the root as deleted. Since cascade delete now happens onSaveChanges, this allows cascade rules to flow to entities later on.
Some important results of this behavior:
- It works as expected for attached scenarios (i.e. non N-Tier scenarios). I.e. if I create a graph of objects and then call
Add, they all get added. - For N-Tier scenarios, it leaves you with the ability to cycle over each entity and tell EF the state (which was blocked in EF6.x because you would get duplicate key exceptions). Of course,
TrackGraphmay also be a better API for these scenarios too.
Activity
ajcvickers commentedon Jan 28, 2016
Nice write up. :-)
Remove GraphBehavior enum and track all reachable entities
julielerman commentedon Feb 1, 2016
:(
Thought I should clarify that ... :) .... sorry you weren't able to work it out. I liked that idea but also know that people are going to have a hard time with changed behavior no matter how many times you tell them "it's not EF6". I'm glad we still have ENTRY to add just the root. It was always a hard problem not being able to tear apart graphs for this purpose so that's still a big win. Agree re great detailed writeup. Thanks. Even Frans said "Tho, reading about the defaults, what they've picked is the best choice for POCOs I think." But he also adds "Root cause is lack of self tracking." (Don't ever bring that back! :) )
tonysneed commentedon Feb 1, 2016
So just to clarify, we'll still be able to set an entity state to Added via TrackGraph and EF will only set the state of that single entity to Added?
rowanmiller commentedon Feb 1, 2016
@tonysneed if you want to set the state of a single entity then
context.Entry(myEntity).State = EntityState.Addedis probably the easiest. TrackGraph will work... but that is really designed for iterating over a graph of entities and setting the state for each one.tonysneed commentedon Feb 1, 2016
Thanks @rowanmiller, so context.Entry(myEntity).State = EntityState.Added will not set child entity states to Added, as it did in EF6. Just wanted to confirm, thanks!
rowanmiller commentedon Feb 1, 2016
@tonysneed correct, EF Core is now ok with having tracked entities reference entities that are not tracked.
tonysneed commentedon Feb 2, 2016
Excellent. In case anyone is interested, Here is a test which shows the difference between EF 6 and EF Core when it comes to setting entity state to Added on a disconnected graph.
Here is the full source code for the tests.
julielerman commentedon Feb 2, 2016
yeah I better go do a RC2 branch and update all of my disconnected data/graph tests in my ef7 repo (https://github.com/julielerman/EF7WhoAreYou/tree/master/Familiar%20and%20Enhancements%20Console%20Full%20NET%20After/Tests.RC)
rowanmiller commentedon Feb 2, 2016
@julielerman and rename your repo to EFCore 😉
BTW our nightly builds are pretty unstable at the moment due to moving over to .NET CLI... so you may want to hold off a couple of weeks.
19 remaining items
divega commentedon Jun 2, 2016
If zero is a valid key you can change the type of the key to be nullable, e.g.
int?instead ofint. ThenIsKeySetwill returntruefor zero andfalsefornull.Not sure what the problem could be. You don't need to make the navigation properties virtual, in fact virtual doesn't make any difference with EF Core. Could you please create a new issue with a self-contained repro of this issue?
johnkwaters commentedon Jun 2, 2016
But then wouldn't I need a nullable pk in the db?
Sent from my iPhone
divega commentedon Jun 2, 2016
No. The column will still be non-nullable as null is not a valid key value in a persisted object. It only means that the key can have a null value temporarily while it is in memory and before it is added to a
DbContext.julielerman commentedon Jun 21, 2016
@ajcvickers when Attaching a graph (no previously tracked entities) and child does NOT have it's key value filled, it becomes Added. When there is a a value in key, it becomes Unchanged. I did not expect this. Is Attach now reading key values to make state decisions? Did I miss that explanation somewhere?
edit: yeah okay I see that re-reading the original post in this thread....
sjb-sjb commentedon Aug 13, 2016
It's great to follow this discussion, especially given how long these challenges have been kicking around.
I believe the TrackGraph pattern described by @julielerman may be superceded by the IsKeySet approach, i.e. simply use store-generated keys and then do one of the following: either
(a) Attach copies of the entities that already exist in the store ("b" in @aflx's example) with their primary keys set, and then Add the (root of the) new entities; or
(b) Refer to existing entities by putting their store-generated keys in the new entities, and then Add the (root of the) new entities.
@julielerman 's comment of June 21, and the description of Attach in @rowanmiller 's original posting, seem to say that in case (a) you could use Attach instead of Add for the new entities. The new entities' store-generated keys will not have been set and therefore the Attach will actually set the state to Added. In other words you can just construct the complete graph, including store-generated Id's in the case where the entity is a copy of an object already in the data store, and just Attach the whole thing. Or you can refer to the existing objects by Id instead of by reference, in which case you can either Add or Attach the graph.
Have I gotten that right? It would be great to have an update to @julielerman 's April MSDN article that takes into account the June discussion above.
ErikEJ commentedon Aug 13, 2016
@sjb-sjb did you see this https://msdn.microsoft.com/magazine/mt767693 ?
sjb-sjb commentedon Aug 15, 2016
Cool, thanks!
Sent from my iPhone
mwpowellhtx commentedon Dec 12, 2025
Not sure the veracity of this claim; as it seems children are prematurely being attached prior to receiving a
nodecallback opportuinity. At which point we would calculate state and so forth, and decide the best course of action, followed sometimes by save changes, at which point those naughty zero identifiers would be triggered to temporarily value generate themselves. This: not happening, in our scenarios...I am using
8(8.0.7) and this STILL seems like a perennial penultimate issue, again. Tracking from a nominally disconnected root instance, and children are STILL being prematurely attach.Because it is gumming up the works, not helping, but rather, proving to be more of a hindrance (read: liability) than a benefit (read: asset), for an arbitrarily n-level disconnected graph scenario. We will not even broach navigation, which are all nominally configured forward only parent-child; no children have navigation to parent, to keep it simple.
Much of the examples are overly simplified, usually with a save changes invoked AFTER tracking graph, which I can tell you for even a minimally complex domain tree/graph, we generally want to calculate state then save changes immediately. That's assuming children have not been prematurely attached to the context.
In our scenarios, we are likely to receive numerous such transient entities from upstream API, and some generated from local application gestures and what not. All disconnected, should be graph tracked in order to properly reconcile with the database, perform appropriate upserts, deletions, etc.
What is the guidance and/or solution on this aspect? Do we need to negotiate the navigation ourselves for a given
node,entry, or what not, as received during the course of graph tracking? It seems perhaps "yes", but the commentary around these nuances seems few if far between.roji commentedon Dec 12, 2025
@mwpowellhtx let's keep that in conversation in #37339 which you opened for this topic. This here is an issue from 2016.