You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Concerning change tracking, it seems as though the DbContext.TrackChanges(...) algorithm is prematurely trying to add transient entities in parent-children navigations.
To summarize our questions and concerns... Are we doing something wrong? Is there a better way to engage with the change tracker? Do we have to intervene and negotate the navigations for id value generation purposes? And if so, what's the point of leaning into the framework in the first place over change tracking, if it is not going to negotiate this issue for us? i.e. I fail to see the value add, in that case, pardoning of course the facetious pun. Is it a bug? Or a feature was added in a subsequent EF core version?
In terms of entity configuration, all navigations are configured forward only that is parent-children; there ought to be no inverse cycles introduced in the other direction i.e. child-parent, as far as I know, not by my configurations.
I have a case where a parent entity is seeing a navigation, i.e. the EntityEntryGraphNode, and we calculate the expected EntityStatefor that node only. My understanding is that the tracker should do subsequent parent-child navigation for us.
However, we are also finding that the transient children for the parent are being added prematurely not as part of this navigation process, for whatever reason, without ever landing in the change tracker node callback.
Entity ids are being configured ValueGeneratedOnAdd(), and we have verified that, when this is properly engaged, the transient ids are being assigned as expected.
However, when children are prematurely being added, this value generation is not happening.
This bit of contention emitting from deepseek, I take some umbrage with the third point, because IMO what is the point of having a change tracking callback node at all, if EF fails to navigate to the chidren using the same callback???
What deepseek claims, which to me, experientially based on what I am seeing, seems accurate. Anyone know anything about this re: change tracker, track graph callbacks?
Again the plumbing is configured re: ValueGeneratedOnAdd() and "works" to a point, except in this instance, which defeats the purpose of it being configured at all.
Note our instances operate in a disconnected environment. That is a must. We are also (appropriately) doing internal bookkeeping to identify transient from persistent, marked for deletion, and so forth, so that is not the issue.
The Root Cause
EF Core's change tracker operates on the principle that once it starts tracking an entity, it will "fix up" all navigations to maintain a consistent graph. When you attach a parent entity, EF will:
Mark the parent as Added or Modified based on its key
Traverse navigations to children
Add those children to the change tracker with a state determined by EF's heuristics
The problem is that EF often misidentifies the state of these "discovered" entities, and the ValueGeneratedOnAdd() configuration doesn't trigger for entities added this way.
Can it be attached? I'll try. I think this is about as minimum as possible with only a little bit of service collection scaffold there. Demonstrates in a simple case, overly academic, perhaps, university has many students and student has many courses.
Built on postgres.
Database scripts are all there, and depends on an environment variable for connection string.
Also uses pgcrypto extensions for purposes of supporting gen_random_uuid().
Guessing that we need to manually traverse some navigations in order to ensure transient identifiers are healthy in order for the context to properly add, modify, etc.
However, curious second and third opinions in pursuit of the same.
So... to elaborate on the above attached example, we can receive disconnected additions (or modifications, and occasionally deletions) in batch, so we need to be able to respond to those accordingly. So far from what I can gather, this is not possible using the disconnected change tracking method. Disconnected is a must. Therefore also change tracking apparently is the preferred approach. Open to suggestions how better we could approach it. The primary issue with the entity states being, especially in terms of additions, more than one addition and the whole thing falls over due to key violations in the context, this in spite of the fact we're training the context how to handle ValueGenerationOnAdd. Perhaps this is something that improved in more recent package versions since 8.0?
@mwpowellhtx I've looked at your repo, but I'm not entirely clear on what exactly isn't working the way you expect it to: your sample calls TrackGraph and then stops, so I don't know what your expectations are at that point. Are you getting an exception, are keys getting or not getting generated as expected?
As in the other issues, you've been writing a lot of English above, with all kinds of thoughts and musings going in various directions. To help us help you effectively, what we need is a minimal code sample - as minimal as possible - with a very precise description of what's unexpected, and what you'd expect to happen. Please avoid writing lots of text: a tight, minimal code snippet is worth a thousand words, and the large amounts of text take more time to read and are frankly somewhat confusing.
Ideally, you'd post a single, minimal console app that expresses what you're trying to do and your expectations. For example, add simple Console.WriteLines at the end showing what's happening, and a comment explaining what's wrong and what you're expectation is.
Two things I sprinkled in. First, SaveChanges which triggers temporary ids being generated. Second, when adding, signaling specifically that the metadata IsTemporary. At least in this case, seems to work.
However, I'm not sure I am finding exactly this use case in the actual repo. This is basically the approach I am taking in the actual non-academic project. But still finding that children are for whatever reason being attached without benefit of change tracking navigation.
Oh and also in the configuration, training the shadow property names to be better behaved, i.e. in Student naming the column specifically according to the column name.
Although sidebar might be better if HasColumnName had an Expression<> based variant, but leaving that aside for sake of discussion.
I'm not sure why EF logic appends a "1" quite honestly, inappropriately so. There is no valid reason to do so, least of all when an expression has been provided, i.e.
// University configuration, one-to-many Students...builder.HasMany(p =>p.Students).WithOne(q =>q.University).HasForeignKey(q =>q.UniversityId);// ^^^^^^^^^^^^
In this case, we specify .HasForeignKey(p => p.UniversityId) and we meant it we do not expect EF to take liberties with the naming convention. In a language environment where reason is key and king, that is not unreasonable to expect.
That said, will try to identify the specific case we are dealing with in which children are being attached somehow from previously disconnected.
Still not entirely sure why is it EF wants to prematurely attach children in spite of the change tracker and configured navigations; i.e. the callbacks never occurred. The main issue is, the instances are operating disconnected, and we may see batches of them i.e. all zero identifiers. They ALL need benefit of triggering the temporary value generated identifiers when save changes occurs.
To reiterate as well, we are using 8.0.7, perhaps this concern has been addressed in a later 8 version (minimum), or later, if we need to consider that upgrade as well.
Calling SaveChanges() inside the TrackGraph callback is not supported. When you set entry.State = EntityState.Added on a parent, and then immediately call SaveChanges(), this triggers:
The NavigationFixer.StateChanged event, which runs InitialFixup — this discovers related entities in navigations and either fixes them up (if tracked) or records them as untracked references.
SaveChanges() itself will detect changes and may start tracking additional entities that were referenced but not yet visited by the graph iterator.
This is why children appear to be "prematurely attached" — it's not the graph iterator skipping your callback, it's the navigation fixup and SaveChanges() that pull in related entities through a different code path.
To avoid this, we recommend traversing your object graph and, in the callback, setting the state manually, and marking primary key properties as temporary where ValueGeneratedOnAdd is used. That nudges EF Core to generate IDs when you call SaveChanges. Here’s a barebones example (I didn't try it out with your code though):
context.ChangeTracker.TrackGraph(parentEntity, node =>
{
var entry = node.Entry;
if (entry.IsKeySet)
{
entry.State = EntityState.Unchanged;
}
else
{
entry.State = EntityState.Added;
foreach (var property in entry.Properties)
{
if (property.Metadata.IsPrimaryKey() && property.Metadata.ValueGenerated == ValueGenerated.OnAdd)
{
property.IsTemporary = true;
}
}
}
});
Activity
mwpowellhtx commentedon Dec 10, 2025
This bit of contention emitting from deepseek, I take some umbrage with the third point, because IMO what is the point of having a change tracking callback node at all, if EF fails to navigate to the chidren using the same callback???
What deepseek claims, which to me, experientially based on what I am seeing, seems accurate. Anyone know anything about this re: change tracker, track graph callbacks?
Again the plumbing is configured re:
ValueGeneratedOnAdd()and "works" to a point, except in this instance, which defeats the purpose of it being configured at all.Note our instances operate in a disconnected environment. That is a must. We are also (appropriately) doing internal bookkeeping to identify transient from persistent, marked for deletion, and so forth, so that is not the issue.
The Root Cause
EF Core's change tracker operates on the principle that once it starts tracking an entity, it will "fix up" all navigations to maintain a consistent graph. When you attach a parent entity, EF will:
The problem is that EF often misidentifies the state of these "discovered" entities, and the
ValueGeneratedOnAdd()configuration doesn't trigger for entities added this way.mwpowellhtx commentedon Dec 10, 2025
Can it be attached? I'll try. I think this is about as minimum as possible with only a little bit of service collection scaffold there. Demonstrates in a simple case, overly academic, perhaps, university has many students and student has many courses.
pgcryptoextensions for purposes of supportinggen_random_uuid().Spike.EFCore.ChangeTracking.ValueGenerationOnAdd.zip
Guessing that we need to manually traverse some navigations in order to ensure transient identifiers are healthy in order for the context to properly add, modify, etc.
However, curious second and third opinions in pursuit of the same.
Best!
mwpowellhtx commentedon Dec 11, 2025
So... to elaborate on the above attached example, we can receive disconnected additions (or modifications, and occasionally deletions) in batch, so we need to be able to respond to those accordingly. So far from what I can gather, this is not possible using the disconnected change tracking method. Disconnected is a must. Therefore also change tracking apparently is the preferred approach. Open to suggestions how better we could approach it. The primary issue with the entity states being, especially in terms of additions, more than one addition and the whole thing falls over due to key violations in the context, this in spite of the fact we're training the context how to handle
ValueGenerationOnAdd. Perhaps this is something that improved in more recent package versions since8.0?roji commentedon Dec 11, 2025
@mwpowellhtx I've looked at your repo, but I'm not entirely clear on what exactly isn't working the way you expect it to: your sample calls TrackGraph and then stops, so I don't know what your expectations are at that point. Are you getting an exception, are keys getting or not getting generated as expected?
As in the other issues, you've been writing a lot of English above, with all kinds of thoughts and musings going in various directions. To help us help you effectively, what we need is a minimal code sample - as minimal as possible - with a very precise description of what's unexpected, and what you'd expect to happen. Please avoid writing lots of text: a tight, minimal code snippet is worth a thousand words, and the large amounts of text take more time to read and are frankly somewhat confusing.
Ideally, you'd post a single, minimal console app that expresses what you're trying to do and your expectations. For example, add simple Console.WriteLines at the end showing what's happening, and a comment explaining what's wrong and what you're expectation is.
mwpowellhtx commentedon Dec 11, 2025
Two things I sprinkled in. First,
SaveChangeswhich triggers temporary ids being generated. Second, when adding, signaling specifically that the metadataIsTemporary. At least in this case, seems to work.However, I'm not sure I am finding exactly this use case in the actual repo. This is basically the approach I am taking in the actual non-academic project. But still finding that children are for whatever reason being attached without benefit of change tracking navigation.
mwpowellhtx commentedon Dec 11, 2025
Oh and also in the configuration, training the shadow property names to be better behaved, i.e. in
Studentnaming the column specifically according to the column name.Although sidebar might be better if
HasColumnNamehad anExpression<>based variant, but leaving that aside for sake of discussion.I'm not sure why EF logic appends a
"1"quite honestly, inappropriately so. There is no valid reason to do so, least of all when an expression has been provided, i.e.In this case, we specify
.HasForeignKey(p => p.UniversityId)and we meant it we do not expect EF to take liberties with the naming convention. In a language environment where reason is key and king, that is not unreasonable to expect.That said, will try to identify the specific case we are dealing with in which children are being attached somehow from previously disconnected.
mwpowellhtx commentedon Dec 11, 2025
The issue I am facing is that EF seems to eagerly attach children instances in spite of the current change tracking node.
mwpowellhtx commentedon Dec 12, 2025
Here's an updated project with the mentioned observations.
Spike.EFCore.ChangeTracking.ValueGenerationOnAdd.zip
Still not entirely sure why is it EF wants to prematurely attach children in spite of the change tracker and configured navigations; i.e. the callbacks never occurred. The main issue is, the instances are operating disconnected, and we may see batches of them i.e. all zero identifiers. They ALL need benefit of triggering the temporary value generated identifiers when save changes occurs.
To reiterate as well, we are using
8.0.7, perhaps this concern has been addressed in a later8version (minimum), or later, if we need to consider that upgrade as well.AndriySvyryd commentedon Feb 13, 2026
Calling
SaveChanges()inside theTrackGraphcallback is not supported. When you setentry.State = EntityState.Addedon a parent, and then immediately callSaveChanges(), this triggers:NavigationFixer.StateChangedevent, which runsInitialFixup— this discovers related entities in navigations and either fixes them up (if tracked) or records them as untracked references.SaveChanges()itself will detect changes and may start tracking additional entities that were referenced but not yet visited by the graph iterator.This is why children appear to be "prematurely attached" — it's not the graph iterator skipping your callback, it's the navigation fixup and
SaveChanges()that pull in related entities through a different code path.To avoid this, we recommend traversing your object graph and, in the callback, setting the state manually, and marking primary key properties as temporary where ValueGeneratedOnAdd is used. That nudges EF Core to generate IDs when you call SaveChanges. Here’s a barebones example (I didn't try it out with your code though):
mwpowellhtx commentedon Feb 13, 2026
This is a curious statement, especially when navigating over potentially MANY different instances in a domain graph (or tree).
How is that not supported?
Can only run by experience there; when I DO NOT save the changes after calculating and applying state, then we get exceptions thrown.
We do this throughout the change tracking callback.
mwpowellhtx commentedon Feb 13, 2026
Remember we are running disconnected.