Skip to content

Keep matching null keys when a correlated Where becomes a join - #39365

Merged
AndriySvyryd merged 2 commits into
dotnet:mainfrom
benedict-odonovan:fix/32026-correlated-null-join
Oct 22, 2026
Merged

AndriySvyryd merged 2 commits into
dotnet:mainfrom
benedict-odonovan:fix/32026-correlated-null-join

Conversation

@benedict-odonovan

Copy link
Copy Markdown
Contributor

Fixes #32026

  • I've read the guidelines for contributing and seen the walkthrough
  • I've posted a comment on an issue with a detailed description of how I am planning to contribute and got approval from a member of the team
  • The code builds and tests pass locally (also verified by our automated build checks)
  • Commit messages follow this format
  • Tests for the changes have been added (for bug fixes / features)
  • Code follows the same patterns and style as existing code in this repo

Summary

A correlated subquery's Where has C# null semantics, so q.Category == p.Category matches rows where both are null. That's how it's translated while it stays a subquery. But when AddJoin turns the subquery into a LEFT JOIN, TryExtractJoinKey moves the comparison into the join predicate. There, SqlNullabilityProcessor.ProcessJoinPredicate treats a lone equality as a LINQ equijoin, where null matches nothing. So the same Where gives different answers:

// Category is a nullable string; posts 3 and 4 have none.
context.Posts.Select(p => new { p.Id, Count = context.Posts.Count(q => q.Category == p.Category) });
// Count = 2 for posts 3 and 4

context.Posts.Select(p => new { p.Id, Ids = context.Posts.Where(q => q.Category == p.Category).Select(q => q.Id).ToList() });
// Ids = [] for posts 3 and 4 (expected [3, 4])

GroupBy hits this when it projects elements together with an aggregate. Those projections aren't lifted by #38963, so each grouping is still correlated with its elements through groupingTerm == elementTerm. The null group then came back as Count = 2 with no elements, which is the bug reported in #32026.

Change

The correlations EF generates itself already say when null keys mustn't match:

  • navigation expansion builds outer != null && outer == inner for a collection navigation;
  • the GroupJoin conversion builds the same guard.

RemoveRedundantNullChecks then removes that guard while extracting the join key, relying on the equijoin semantics of a lone join equality (see #35706).

So TryExtractJoinKey now reports whether the extracted predicate is a lone equality from which no such null check was removed. In that case, AddJoin gives the equality the always-true partner that CreateJoinPredicate already uses for a single-property anonymous type. ProcessJoinPredicate then processes it with C# null semantics: [a] = [b] OR ([a] IS NULL AND [b] IS NULL) for nullable columns, and nothing extra for non-nullable ones. Under UseRelationalNulls(), the predicate stays a plain =.

Composite correlations already took this path, because an AndAlso gets the regular null-semantics treatment.

Behavior change

A correlated collection over nullable keys now includes the rows where both keys are null. That matches LINQ, and matches the same correlation in an aggregate. The SQL of such joins gains an OR ... IS NULL term, which can affect the plan the database picks. Both the result change and the plan change may be worth a breaking-change note.

Tests

  • NullSemanticsQueryTestBase:
    • Correlated_collection_uses_csharp_semantics, which failed before;
    • Correlated_collection_uses_csharp_semantics_with_composite_correlation;
    • Correlated_collection_using_relational_null_semantics, where null keys still don't match.
  • NorthwindGroupByQueryTestBase: GroupBy_nullable_key_selecting_grouping_element_list_with_aggregate, the No items when projecting out groupings with a null key #32026 case over Customers.Region, which failed before.
  • Baselines updated for existing grouping-element projections, Distinct and user-written correlations over nullable keys. Every changed baseline line is the same ON with the OR ... IS NULL compensation added. No navigation or GroupJoin join changed.

I ran the full Microsoft.EntityFrameworkCore.Query namespace locally against LocalDB: 15,364 tests on SQL Server and 12,728 on SQLite. With the updated baselines, everything passes. Since the spec tests compare against LINQ-to-Objects, no result changed except where it now matches LINQ.

- A correlated subquery's Where has C# null semantics: q.Category == p.Category matches rows where both are null. When the
  subquery was turned into a LEFT JOIN, the comparison became a lone equality in the join predicate, which
  SqlNullabilityProcessor processes as a LINQ equijoin - null matching nothing - so ToList() over the subquery lost the rows a
  Count() over the same Where kept. GroupBy projecting its elements alongside an aggregate correlates the groupings with their
  elements this way, so the group with a null key came back with no elements.
- Correlations which do want null keys to match nothing (navigations, GroupJoin) state it with a null check on the outer key,
  which extraction removes as redundant. A lone extracted equality without one is now given an always-true partner, as
  CreateJoinPredicate does for an anonymous type with a single property, so that it's processed with C# null semantics.
- Add tests for correlated collections over nullable keys, with C# and relational null semantics, and for a GroupBy over a
  nullable key projecting its elements and an aggregate; update the baselines of grouping element projections over nullable
  keys.

Fixes dotnet#32026
@benedict-odonovan
benedict-odonovan requested a review from a team as a code owner October 22, 2026 13:02
Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

- JsonQueryJsonTypeSqlServerTest only runs against SQL Server 2025, so its Group_by_Skip_Take_on_json_scalar baseline was missed
  when the JsonQuerySqlServerTest one gained the null compensation.
Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The shared rewrite changes results and query plans across relational providers, warranting maintainer validation despite the focused regression coverage.

No open issues 🎉

Review effort: Balanced

@AndriySvyryd AndriySvyryd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution!

@AndriySvyryd
AndriySvyryd merged commit 079c5b9 into dotnet:main Oct 22, 2026
19 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No items when projecting out groupings with a null key

3 participants