Skip to content

Don't scaffold a foreign key as one-to-one when its unique index is filtered - #39574

Merged
AndriySvyryd merged 4 commits into
dotnet:mainfrom
ajcvickers:fix/11298-filtered-unique-index-fk
Nov 17, 2026
Merged

AndriySvyryd merged 4 commits into
dotnet:mainfrom
ajcvickers:fix/11298-filtered-unique-index-fk

Conversation

@ajcvickers

Copy link
Copy Markdown
Contributor

Fixes #11298

Problem

When reverse engineering, a foreign key was scaffolded as one-to-one whenever a unique index existed over exactly its columns. The index filter was ignored. A filtered unique index only guarantees uniqueness for the rows that satisfy the filter, so the relationship can still be one-to-many. The generated reference navigation then throws as soon as several dependents share a principal, for example with the soft-delete/"only one active row" pattern from the issue:

CREATE UNIQUE INDEX [IX_PersonRole_PersonId] ON [PersonRole]([PersonId]) WHERE [IsActive] = 1

Fix

RelationalScaffoldingModelFactory now counts a unique index towards making the foreign key unique only if its filter is absent or is a null guard: IS NOT NULL terms joined by AND, each on one of the foreign key's own columns. That is the filter providers generate by convention for unique indexes over nullable columns (e.g. SQL Server's [col] IS NOT NULL), and rows excluded by it don't take part in the relationship, so optional one-to-one relationships stay one-to-one.

This is a conservative pattern match, not SQL parsing, so it doesn't need #10183. Anything it doesn't recognize is treated as restricting rows, which gives a collection navigation. That is always valid for the data, whereas wrongly assuming uniqueness gives a navigation that can throw. Identifiers may be quoted as [x], "x" or `x`, or bare; column names are matched against the database column names. Both regexes use the usual 1 second timeout, and a timeout is treated as "restricting".

SQLite never read index filters, so a partial unique index was scaffolded as a plain unique index (wrong navigation, and HasFilter missing from the scaffolded code). It now reads partial from pragma_index_list, and for those indexes takes the filter from the original statement in sqlite_master: the text after the first WHERE outside quotes, comments and parentheses, with comments removed. This needs a small scanner but no SQL grammar. As a result, AssertIndexFilters is now enabled for the SQLite migrations tests, which round-trips filters created by EF.

Behavior change

Re-scaffolding a database that has a filtered unique index over a foreign key's columns, other than the null guard above, now produces a collection navigation (WithMany) instead of a reference navigation (WithOne). The index itself is still scaffolded as unique with its filter. On SQLite, partial indexes now also get HasFilter(...) in the scaffolded code.

Not changed

Tests

  • Design: null-guard matching (quoting styles, bare identifiers, multi-column and renamed/escaped columns, mixed predicates, several indexes over the same columns, very long inputs), and code generation of HasFilter text containing quotes, line breaks and braces.
  • SQL Server: the repro from the issue, an optional one-to-one with a convention filter, and composite foreign keys.
  • SQLite: filter extraction (comments, quotes, statement forms) and end-to-end foreign key uniqueness.

🤖 Generated with Claude Code

@ajcvickers
ajcvickers requested a review from a team as a code owner November 9, 2026 12:34
Copilot AI balanced review requested due to automatic review settings November 9, 2026 12:34

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 insufficient remaining quota. Try requesting a review at a lower effort level.

@ErikEJ

ErikEJ commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

@ajcvickers Awesome, this has tripped up many EF Core Power Tools users

@ajcvickers

Copy link
Copy Markdown
Contributor Author

@AndriySvyryd Do you want a breaking change for this? The same database now results in a different EF model.

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.

🟡 Changes recommended

Unresolved critical bugs can incorrectly infer one-to-one relationships where foreign keys are not unique, while SQLite filter parsing can also produce invalid predicates.

3 open issues

Review effort: Balanced

…iltered

A unique index with a filter only guarantees uniqueness for the rows that satisfy
the filter, so a foreign key over the same columns can still be one-to-many.
Reverse engineering ignored the filter and generated a reference navigation, which
throws at runtime once several dependents exist.

A unique index now makes the foreign key one-to-one only if it has no filter or the
filter just excludes rows where the foreign key columns are null (the filter that
providers generate by convention for unique indexes over nullable columns). That is
recognized with a conservative pattern match, not by parsing SQL: anything not
recognized is treated as restricting, which results in a collection navigation.

SQLite never read index filters, so partial unique indexes were scaffolded as plain
unique indexes. The filter text is now read from sqlite_master for indexes that
pragma_index_list reports as partial, and index filters are asserted in the
SQLite migrations round-trip tests.

Fixes dotnet#11298

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@ajcvickers
ajcvickers force-pushed the fix/11298-filtered-unique-index-fk branch from 0093d20 to 02fc8dd Compare November 14, 2026 12:01
Copilot AI balanced review requested due to automatic review settings November 14, 2026 12:01

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 insufficient remaining quota. Try requesting a review at a lower effort level.

ajcvickers and others added 3 commits November 14, 2026 16:57
…the SQLite index filter

SQLite allows any character at or above U+0080 in an unquoted identifier, but the scan for the WHERE keyword only treated letters, digits, '_' and '$' as identifier characters. An index named, for example, `where☃` was taken to start the filter at the index name, which produced an invalid HasFilter predicate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… ignoring case

A database that distinguishes columns by case (SQL Server with a case-sensitive collation, or SQLite with non-ASCII letters) can have both `PersonId` and `personid`. The null-guard check compared filter names with the foreign key columns ignoring case, so a unique index on one column filtered by the other column's IS NOT NULL was taken as a null guard, and the foreign key was scaffolded as one-to-one even though duplicate values are allowed when the other column is null.

Filter names are now resolved against all the columns of the table: an exact match wins, and the case-insensitive fallback is used only when it identifies a single column.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A foreign key column named "NULL" matched the bare identifier in `NULL IS NOT NULL`, so a unique index with that always-false filter was taken as a null guard and the foreign key was scaffolded as one-to-one. A bare NULL is the keyword and is now treated as restricting the rows; a quoted "NULL" is still a column.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 14, 2026 17:21

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 insufficient remaining quota. Try requesting a review at a lower effort level.

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 custom SQLite scanner and regex-based filter classifier influence relationship cardinality and generated migrations, warranting human validation of unusual SQL forms and provider compatibility.

No open issues 🎉

3 resolved since last review

Review effort: Lite

@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 ffbe670 into dotnet:main Nov 17, 2026
19 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 18, 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.

Scaffold-DbContext generates incorrect nav property on foreign key with filtered unique index

4 participants