Why EF Core ThenInclude navigations are null after ToList() but not in a foreach
A one-to-one relationship mapped over a foreign key that is not unique in the database makes EF Core's fixup steal the navigation from earlier rows. foreach reads them before the theft, ToList() after. SaveChanges() then deletes the orphaned rows. Map it as one-to-many.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
If Include(...).ThenInclude(...) fills a reference navigation while you stream the query in a foreach, but the same navigation is null on some entities once you call ToList(), the cause is almost never ToList(). You have mapped a one-to-one relationship (HasOne(...).WithOne(...)) over a foreign key column that is not unique in the actual table. EF Core believes each principal can have only one dependent, so when a second row pointing at the same principal is materialized, relationship fixup moves the navigation to the new row and nulls it on the old one. In a foreach you look at each entity before the next one steals its navigation; after ToList() you look at everything after the fact. Worse, the stolen-from rows are marked Deleted, and the next SaveChanges() removes them. Fix the model: map the relationship as one-to-many with WithMany(...). Everything below was reproduced on EF Core 11.0.0 (.NET SDK 11.0.100) and EF Core 10.0.15 (.NET SDK 10.0.403) with SQLite on macOS arm64, with identical results on both.
The shape of the bug
This comes from a Stack Overflow question with a classic database-first schema: Article, a link table DescriptionLink, and Description. Articles have many links, and the link-to-description side was configured like this:
// EF Core 11.0.0 / 10.0.15 -- the configuration that causes the problem
modelBuilder.Entity<DescriptionLink>()
.HasOne(l => l.DescriptionPart)
.WithOne(d => d.LinkToArticle) // one-to-one
.HasForeignKey<DescriptionLink>(l => l.DescriptionId)
.HasPrincipalKey<Description>(d => d.DescriptionId);
Streaming the query worked. Materializing it first, to know the count for a progress bar, did not:
// Works: every link has its DescriptionPart while you are inside the loop
foreach (var article in db.Articles
.Include(a => a.DescLinks).ThenInclude(l => l.DescriptionPart)
.Where(a => a.Category == "tools"))
{
var parts = article.DescLinks.Select(l => l.DescriptionPart); // all non-null
}
// "Broken": some DescriptionPart values are null
var articles = db.Articles
.Include(a => a.DescLinks).ThenInclude(l => l.DescriptionPart)
.Where(a => a.Category == "tools")
.ToList();
The SQL is the same in both cases. What differs is when you read the navigations relative to what the change tracker does while the rest of the result set is materialized.
Why a one-to-one mapping turns shared rows into a tug of war
In a one-to-one relationship the foreign key on the dependent is unique: a principal can be referenced by at most one dependent row. You can confirm that EF Core built the model that way:
// EF Core 11.0.0
foreach (var fk in db.Model.FindEntityType(typeof(DescriptionLink))!.GetForeignKeys())
Console.WriteLine($"FK {string.Join(",", fk.Properties.Select(p => p.Name))} " +
$"IsUnique={fk.IsUnique} IsRequired={fk.IsRequired} DeleteBehavior={fk.DeleteBehavior}");
FK ArticleReference IsUnique=False IsRequired=True DeleteBehavior=Cascade
FK DescriptionId IsUnique=True IsRequired=True DeleteBehavior=Cascade
Database.GenerateCreateScript() for the same model emits the index EF expects to exist:
CREATE UNIQUE INDEX "IX_DescriptionLinks_DescriptionId" ON "DescriptionLinks" ("DescriptionId");
If the database had been created from this model, the second link to the same description would have been rejected at insert time. But in the question the table came from somewhere else, and in the real data the same description is reused by several articles. EF Core never compares its model with the database schema, so nothing tells you the two disagree.
Now walk through what the change tracker does when a tracking query returns two DescriptionLink rows with the same DescriptionId:
- Link 1 (
DescriptionId = 1) is tracked. Fixup setslink1.DescriptionPart = description1anddescription1.LinkToArticle = link1. - Later in the same result set, link 3 (
DescriptionId = 1as well) is tracked. Fixup setslink3.DescriptionPart = description1anddescription1.LinkToArticle = link3. - Because the relationship is one-to-one,
description1can have only one dependent. From EF’s point of view link 3 just replaced link 1, exactly as if you had writtendescription1.LinkToArticle = link3yourself. Link 1 has been severed from its principal, so EF nullslink1.DescriptionPart. DescriptionIdis a non-nullableint, so the relationship is required. A dependent of a required relationship that loses its principal is an orphan, and with the defaultDeleteOrphansTimingofImmediatethe orphan is markedDeletedon the spot. The cascade delete documentation describes this orphan deletion behavior.
The last link loaded for each description wins. Every earlier link loses its navigation, and its tracked state becomes Deleted.
Reproducing it end to end
The repro builds a SQLite database with plain SQL (no unique index, like a legacy schema), seeds four links where description 1 and description 2 are each used twice, and maps the entities exactly as in the question.
// .NET 11, EF Core 11.0.0, Microsoft.EntityFrameworkCore.Sqlite 11.0.0
// (also run on .NET 10 with EF Core 10.0.15: same output)
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
const string cs = "Data Source=repro.db";
File.Delete("repro.db");
using (var conn = new SqliteConnection(cs))
{
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
CREATE TABLE Articles (ArticleReference TEXT PRIMARY KEY, Category TEXT NOT NULL);
CREATE TABLE Descriptions (DescriptionId INTEGER PRIMARY KEY, Text TEXT NOT NULL);
CREATE TABLE DescriptionLinks (
Id INTEGER PRIMARY KEY,
ArticleReference TEXT NOT NULL REFERENCES Articles(ArticleReference),
DescriptionId INTEGER NOT NULL REFERENCES Descriptions(DescriptionId));
INSERT INTO Articles VALUES ('A1','tools'), ('A2','tools'), ('A3','tools');
INSERT INTO Descriptions VALUES (1,'Steel'), (2,'Waterproof');
INSERT INTO DescriptionLinks VALUES (1,'A1',1), (2,'A1',2), (3,'A2',1), (4,'A3',2);
""";
cmd.ExecuteNonQuery();
}
static void Print(Article a) => Console.WriteLine($" {a.ArticleReference}: " + string.Join(", ",
a.DescLinks.Select(l => $"link{l.Id}->{l.DescriptionPart?.Text ?? "null"}")));
static IQueryable<Article> Query(ShopContext db) => db.Articles
.Include(a => a.DescLinks).ThenInclude(l => l.DescriptionPart)
.Where(a => a.Category == "tools")
.OrderBy(a => a.ArticleReference);
using (var db = new ShopContext(cs))
{
Console.WriteLine("-- streaming foreach, printed inside the loop");
var seen = new List<Article>();
foreach (var a in Query(db)) { Print(a); seen.Add(a); }
Console.WriteLine("-- same tracked instances, after the loop finished");
seen.ForEach(Print);
}
using (var db = new ShopContext(cs))
{
Console.WriteLine("-- ToList()");
Query(db).ToList().ForEach(Print);
foreach (var e in db.ChangeTracker.Entries<DescriptionLink>())
Console.WriteLine($" tracker: link{e.Entity.Id} {e.State}");
Console.WriteLine($" SaveChanges() affected {db.SaveChanges()} row(s)");
}
using (var db = new ShopContext(cs))
Console.WriteLine($"-- rows left in DescriptionLinks: {db.Set<DescriptionLink>().Count()}");
public class Article
{
public string ArticleReference { get; set; } = "";
public string Category { get; set; } = "";
public List<DescriptionLink> DescLinks { get; set; } = [];
}
public class DescriptionLink
{
public int Id { get; set; }
public int DescriptionId { get; set; }
public string ArticleReference { get; set; } = "";
public Article? DescribedArticle { get; set; }
public Description? DescriptionPart { get; set; }
}
public class Description
{
public int DescriptionId { get; set; }
public string Text { get; set; } = "";
public DescriptionLink? LinkToArticle { get; set; }
}
public class ShopContext(string cs) : DbContext
{
public DbSet<Article> Articles => Set<Article>();
protected override void OnConfiguring(DbContextOptionsBuilder o) => o.UseSqlite(cs);
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Article>().HasKey(a => a.ArticleReference);
b.Entity<Description>().ToTable("Descriptions").HasKey(d => d.DescriptionId);
b.Entity<DescriptionLink>().ToTable("DescriptionLinks");
b.Entity<Article>()
.HasMany(a => a.DescLinks).WithOne(l => l.DescribedArticle)
.HasPrincipalKey(a => a.ArticleReference).HasForeignKey(l => l.ArticleReference);
b.Entity<DescriptionLink>()
.HasOne(l => l.DescriptionPart).WithOne(d => d.LinkToArticle)
.HasForeignKey<DescriptionLink>(l => l.DescriptionId)
.HasPrincipalKey<Description>(d => d.DescriptionId);
}
}
Output, identical on EF Core 11.0.0 and 10.0.15:
-- streaming foreach, printed inside the loop
A1: link1->Steel, link2->Waterproof
A2: link3->Steel
A3: link4->Waterproof
-- same tracked instances, after the loop finished
A1: link1->null, link2->null
A2: link3->Steel
A3: link4->Waterproof
-- ToList()
A1: link1->null, link2->null
A2: link3->Steel
A3: link4->Waterproof
tracker: link1 Deleted
tracker: link2 Deleted
tracker: link3 Unchanged
tracker: link4 Unchanged
SaveChanges() affected 2 row(s)
-- rows left in DescriptionLinks: 2
The second block is the giveaway. The foreach did not “work”: the very same Article instances it printed correctly have lost their navigations by the time the loop ends. ToList() only changes when you look.
The last two lines are the part that should worry you more than the nulls. Any code path that runs this query and then calls SaveChanges() for an unrelated reason (updating a timestamp on one article, say) silently deletes link rows from the database.
Watching the steal happen in the change tracker log
Turn on debug logging for the change tracking category and the sequence from the previous section is spelled out:
// EF Core 11.0.0
o.UseSqlite(cs)
.EnableSensitiveDataLogging()
.LogTo(Console.WriteLine, [DbLoggerCategory.ChangeTracking.Name], LogLevel.Debug);
CoreEventId.StartedTracking[10806] Context 'ShopContext' started tracking 'Article' entity with key '{ArticleReference: A2}'.
CoreEventId.ReferenceChangeDetected[10805] The navigation 'DescriptionLink.DescriptionPart' for entity with key '{Id: 3}' was detected as changed.
CoreEventId.StateChanged[10807] The 'DescriptionLink' entity with key '{Id: 1}' tracked by 'ShopContext' changed state from 'Unchanged' to 'Modified'.
CoreEventId.StateChanged[10807] The 'DescriptionLink' entity with key '{Id: 1}' tracked by 'ShopContext' changed state from 'Modified' to 'Deleted'.
CoreEventId.ReferenceChangeDetected[10805] The navigation 'DescriptionLink.DescriptionPart' for entity with key '{Id: 1}' was detected as changed.
CoreEventId.ReferenceChangeDetected[10805] The navigation 'Description.LinkToArticle' for entity with key '{DescriptionId: 1}' was detected as changed.
Link 3 arrives with article A2, and in the same instant link 1, which belongs to A1, goes Unchanged to Modified to Deleted and loses its DescriptionPart. If you ever see a StateChanged ... to 'Deleted' entry during a plain query, look for exactly this kind of model and data mismatch.
Why it looked random in the real application
Three things make this hard to pin down from symptoms alone:
- Only shared rows break. If a description is used by one article in the result set, nothing is stolen. Loading article A1 on its own with
Single(a => a.ArticleReference == "A1")printedlink1->Steel, link2->Waterproofbecause links 3 and 4 were not in that result set. Unit tests with tidy seed data usually pass. - The filter changes the outcome. Whether two links to the same description land in the same result set depends on the
Whereclause, so the bug comes and goes with user input. - Which row wins depends on row order. The last link materialized keeps the navigation. Without an
OrderBy, the database decides that order, so the “broken” article can change between runs or after an index rebuild.
The fix: tell EF Core the truth about the relationship
If one description can be shared by many links, the relationship is many-to-one from the link’s side. Replace the reference navigation on Description with a collection and use WithMany:
// EF Core 11.0.0 / 10.0.15
public class Description
{
public int DescriptionId { get; set; }
public string Text { get; set; } = "";
public List<DescriptionLink> DescLinks { get; set; } = []; // was: DescriptionLink? LinkToArticle
}
modelBuilder.Entity<DescriptionLink>()
.HasOne(l => l.DescriptionPart)
.WithMany(d => d.DescLinks)
.HasForeignKey(l => l.DescriptionId);
The model now reports FK DescriptionId IsUnique=False, and the same program prints:
-- streaming foreach, printed inside the loop
A1: link1->Steel, link2->Waterproof
A2: link3->Steel
A3: link4->Waterproof
-- same tracked instances, after the loop finished
A1: link1->Steel, link2->Waterproof
A2: link3->Steel
A3: link4->Waterproof
-- ToList()
A1: link1->Steel, link2->Waterproof
A2: link3->Steel
A3: link4->Waterproof
tracker: link1 Unchanged
tracker: link2 Unchanged
tracker: link3 Unchanged
tracker: link4 Unchanged
SaveChanges() affected 0 row(s)
-- rows left in DescriptionLinks: 4
You do not have to expose the collection if you do not need it. .WithMany() with no argument is enough to make the foreign key non-unique.
If the relationship really is supposed to be one-to-one and the duplicates are bad data, fix the data instead and add the unique index the model already assumes. Either way, the model and the schema have to agree. To find out whether they do, query the table directly:
-- Any rows here mean a one-to-one mapping on DescriptionId is wrong for this data
SELECT DescriptionId, COUNT(*) AS Links
FROM DescriptionLinks
GROUP BY DescriptionId
HAVING COUNT(*) > 1;
It is worth running that check for every WithOne in a database-first model. The same mismatch is what a scaffolder produces when it treats a filtered unique index as a one-to-one relationship, and it ends in the same deleted rows.
Workarounds that hide the symptom, and ones that do not
Each of the usual suspects was run against the unfixed one-to-one model, on both EF Core versions:
| Query shape | A1’s navigations | Notes |
|---|---|---|
Tracking ToList() | null | links 1 and 2 marked Deleted |
AsNoTracking().ToList() | filled | each link gets its own Description instance, so nothing is stolen |
AsNoTrackingWithIdentityResolution().ToList() | null | identity resolution runs the same fixup |
AsSplitQuery().ToList() | null | splitting changes the SQL, not the fixup |
ChangeTracker.DeleteOrphansTiming = CascadeTiming.Never | null | links become Modified; SaveChanges() throws |
AsNoTracking() makes the nulls go away because, without identity resolution, a no-tracking query creates a separate Description object for every row and there is no shared principal to fight over. The tracking vs. no-tracking documentation explains that difference, and the AsNoTracking vs AsNoTrackingWithIdentityResolution comparison goes deeper into what each one shares. It is a fine choice for a read-only report, but it leaves the wrong model in place for the next tracking query, and you get one Description object per link instead of one per description.
Split queries are a good tool against cartesian explosion, but they do not help here: the related rows still flow through the same tracker.
Setting DeleteOrphansTiming to Never stops the immediate Deleted state, but the navigations are still nulled and SaveChanges() then fails with:
InvalidOperationException: The association between entity types 'Description' and 'DescriptionLink' has been severed, but the relationship is either marked as required or is implicitly required because the foreign key is not nullable.
That is safer than silently deleting rows, which makes it a reasonable temporary guard while you fix the model, but it is not a fix.
Things that are not the cause
ToList()versusforeach. Both run one query and both materialize the same entities into the same tracker.foreachonly lets you observe each entity before the rows after it are materialized, which is why the repro’sforeachprinted correct values for instances that were already broken when the loop ended.Includeordering orThenIncludesyntax. The query returns every link row; the navigations are lost afterwards, during fixup.ToQueryString()shows the SQL if you want to check it against your own model.- A bug in EF Core. Fixup is doing what the model told it: one description, one link. The relationship changes documentation describes how fixup keeps both ends of a relationship consistent when a navigation or foreign key changes, and a query that tracks a second dependent for the same principal is one of those changes.
If your code depends on what EF writes into tracked entities beyond the query results, what EF Core writes back into an entity after SaveChangesAsync covers the other side of fixup.
Sources
- Stack Overflow: ThenInclude() does not appear to work with ToList()
- One-to-one relationships, EF Core docs
- Changing foreign keys and navigations, EF Core docs
- Cascade delete and orphan deletion timing, EF Core docs
- Tracking vs. no-tracking queries, EF Core docs
- Eager loading of related data, EF Core docs
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.