Skip to content

Fix JSON collection element property named "key" colliding with the array index column - #39475

Merged
AndriySvyryd merged 1 commit into
dotnet:mainfrom
vbornand:fix/39438-json-key-column
Oct 31, 2026
Merged

AndriySvyryd merged 1 commit into
dotnet:mainfrom
vbornand:fix/39438-json-key-column

Conversation

@vbornand

@vbornand vbornand commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #39438

A JSON property named key in an element of a JSON collection collided with the index column of the JSON table-valued function (OPENJSON's [key] on SQL Server, json_each's key on SQLite), because CreateSelect names the element columns after their JSON property names.

  • SQL Server: projecting the elements ordered by CAST(JSON_VALUE([a].[value], '$.key') AS int) instead of CAST([a].[key] AS int), failing with a conversion error.
  • SQLite: the outer identifier and ordering bound to the property and failed with "No coercion operator…". This also happened with Key in any casing, since subquery aliases are made unique case-insensitively.

Fix

  • New internal GetJsonElementColumnName hook in CreateSelect. It returns the JSON name by default, so other providers are unaffected.
  • SQL Server renames a WITH column named key to the first name among key0, key1… not used by another WITH column. The JSON path stays '$.key'.
  • SQLite does the same for the subquery alias over json_each, and reads the actual alias back.
  • Names without a collision are kept, as discussed in the issue.

Design notes

  • The property column is renamed rather than the index column: OPENJSON's [key] is a built-in column on SQL Server, and on SQLite the key name is matched in several places (ElementAt translation, natural ordering detection, type mapping postprocessing).
  • SQL Server detects key case-sensitively: a property named Key already works there (column names are compared ordinally, and [key] is only referenced once the WITH clause is removed), so renaming it would change its SQL for nothing. SQLite detects it case-insensitively, because EF makes subquery aliases unique case-insensitively, which is what broke Key there.

Tests (JsonQueryRelationalTestBase, with SQL baselines for SQL Server nvarchar(max) and json columns, and SQLite):

  • projection, and projection with Take (SQLite: known APPLY limitation);

  • filter with Any, where the WITH clause is kept and shows the renamed column;

  • Key in capitals;

  • key next to key0 (key becomes key1), and key0 alone (kept);

  • a nested complex property named key;

  • an owned collection (OwnsMany().ToJson()) with a property named key.

  • 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

Copilot AI balanced review requested due to automatic review settings October 30, 2026 21:10
@vbornand
vbornand requested a review from a team as a code owner October 30, 2026 21:10
…rray index column

- Add an internal GetJsonElementColumnName hook to CreateSelect so providers can name element columns
- SQL Server: rename an OPENJSON WITH column named "key" to the first free name among key0, key1... so it doesn't collide with OPENJSON's [key] index column
- SQLite: do the same for the subquery alias over json_each, case-insensitively since aliases are unique case-insensitively
- Names without a collision are kept

Fixes dotnet#39438
@vbornand
vbornand force-pushed the fix/39438-json-key-column branch from d373998 to e45170a Compare October 30, 2026 21:13

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 change spans the shared relational CreateSelect JSON-projection path and two provider overrides with non-obvious column aliasing, whose correctness depends on provider SQL baselines that can't be verified without executing tests here.

No open issues 🎉

What changed in this PR

This PR fixes issue #39438, where a JSON collection element property whose JSON name is key collided with the array-index column of the JSON table-valued function (OPENJSON's [key] on SQL Server, json_each's key on SQLite). Because CreateSelect names element columns after their JSON property names, the property column and the index column both became key, causing the ordering (CAST([a].[key] AS int)) to resolve to the property value and fail (SQL Server conversion error; SQLite coercion error). The fix introduces a provider-overridable hook that renames the colliding property column while leaving the index column named key.

Changes:

  • Added internal GetJsonElementColumnName hook in CreateSelect (default returns the JSON name unchanged, so other relational providers are unaffected), and routed the three JSON column-creation sites (property, complex container, owned navigation) through it.
  • SQL Server renames the colliding WITH column (key → first free key0/key1…, detected case-sensitively) keeping the JSON path '$.key'; the override reads the renamed name back by matching on path.
  • SQLite renames the json_each subquery alias (detected case-insensitively, matching how EF uniquifies subquery aliases) and reads the actual alias back from the pushed-down subquery projection.
  • Added comprehensive relational specification tests (projection, Take, Any filter with WITH, Key casing, key+key0, key0 alone, nested complex key, owned collection) with SQL Server (nvarchar(max) and json) and SQLite baselines.

Assessment: I traced the renaming loops (no infinite-loop risk; key/key+key0/key0-alone scenarios all produce correct names), verified the index column stays key so natural-ordering/ElementAt/FindJsonElement detection keeps working, and confirmed the [EntityFrameworkInternal] base member and the overrides are both excluded from the API baseline (no baseline update required). The base behavior is unchanged for non-overriding providers, so the change is backward-compatible. All 8 new virtual tests are overridden in all three provider classes, and the Cosmos suite derives from the non-relational base, so no override guard is impacted. I did not find concrete defects; the fix is well-targeted and comprehensively tested. The one residual gap is that baseline correctness depends on provider SQL generation that I verified by tracing but could not confirm by execution in this environment.

File Description
src/​EFCore.Relational/​Query/​RelationalQueryableMethodTranslatingExpressionVisitor.CreateSelect.cs Adds the GetJsonElementColumnName hook and routes the three JSON column-name sites through it.
src/​EFCore.SqlServer/​Query/​Internal/​SqlServerQueryableMethodTranslatingExpressionVisitor.cs Renames a WITH column named key and overrides the hook to resolve the renamed name by JSON path.
src/​EFCore.Sqlite.Core/​Query/​Internal/​SqliteQueryableMethodTranslatingExpressionVisitor.cs Refactors element collection into a list, computes a free alias for a key-named property, and overrides the hook to read the subquery alias.
test/​EFCore.Relational.Specification.Tests/​Query/​JsonQueryRelationalTestBase.cs Adds the shared #region 39438 regression tests (projection, filter, Take, nested complex, owned) with result assertions.
test/​EFCore.SqlServer.FunctionalTests/​Query/​JsonQuerySqlServerTest.cs Provider overrides with nvarchar(max) SQL baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​JsonQueryJsonTypeSqlServerTest.cs Provider overrides with json-type SQL baselines.
test/​EFCore.Sqlite.FunctionalTests/​Query/​JsonQuerySqliteTest.cs Provider overrides with SQLite baselines, including the Take APPLY-not-supported case.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 30, 2026 21:22

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 change introduces a new internal JSON-collection SQL generation hook with broad provider-wide impact that was only verified by reading SQL baselines, so live-database test confirmation by a human is still needed.

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 94e104b into dotnet:main Oct 31, 2026
18 of 19 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 31, 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.

JSON complex collection with a property mapped to "key" breaks element ordering: OPENJSON index column resolved to the property

3 participants