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
{{ message }}
Repository navigation
Read converted collection identifiers as provider values - #39369
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
A query whose rows are told apart by a value-converted property of a reference type never returns; one core stays at 100%. Two examples:
// Tag is a class without Equals, mapped with HasConversion(t => t.Name, n => new Tag { Name = n })context.Posts.GroupBy(p =>p.Tag).Select(g =>new{g.Key,Ids=g.Select(p =>p.Id).ToList(),Count=g.Count()});context.Posts.Select(p =>p.Tag).Distinct().Select(t =>new{Tag=t,Ids=context.Posts.Where(p =>p.Tag==t).Select(p =>p.Id).ToList()});
Cause.
A collection shaper tells its rows apart by identifier values. When a query has no entity key to identify its rows by (grouping terms, a Distinct projection, set-operation columns), SelectExpression uses those columns as identifiers.
Each identifier read materializes a new Tag through the converter, and the default key comparer for a class without Equals falls back to reference equality. So an identifier never equals the one just read from the same row.
The collection shaper then ends the collection and sets HasNext = true without advancing the reader, which makes the same row the start of the next parent, again and again.
Change. A collection's identifiers are now read and compared as the database returned them, the way the database told the rows apart when it grouped or applied DISTINCT:
Where an identifier column's type mapping has a value converter, the identifier accessor wraps its projection binding in a new internal ProviderValueProjectionBindingExpression and pairs it with the mapping's ProviderValueComparer. Every other identifier keeps its accessor and comparer, as before.
The shaper reads that node with the converter skipped (a new applyConverter flag on CreateGetValueExpression). The node never survives shaper processing, so precompiled queries are unaffected.
The decision is made where identifier accessors are built, not where identifiers are collected. It covers every path that contributes identifiers: entity keys, ApplyDistinct (including the columns of a distinct complex type and the non-key properties of a JSON-owned entity), both ApplyGrouping overloads, and both set-operation paths. It also covers single and split queries.
The generated SQL doesn't change: the identifier columns were already projected.
Final GroupBy is the exception. Its key identifier isn't a row's identity but the LINQ grouping key, which LINQ compares as the model value. So it's still read through the converter and compared with the key comparer. With a converter that reads different database values as the same one ("1" and "01" through int.Parse), comparing provider values would have produced two groupings with key 1. A converted reference type without Equals as a final GroupBy key gives one grouping per row, as LINQ to Objects does with reference equality, and doesn't hang.
Behavior change. This applies to every converted collection identifier, not only reference types that compare by reference: enums and strongly typed IDs are now compared as their provider values too. That gives the same result for any converter that reads each database value as a distinct model value. With one that doesn't, the collection shapes now follow the database. For example, rows with "1" and "01" in a Distinct() + correlated collection, or a GroupBy with an element list, come back as two results with model value 1. On main they were merged on the client, which mixed aggregates computed per database group: the merged group listed all three posts but its Count() was 1.
Alternatives considered
Compare the materialized values with a comparer that converts them back to provider values. This was the first version of this PR. It needed a reflection check on the model type (an Equals override, ==, interfaces, structural equality) to decide which types compare by reference. It also ran the write converter, which needn't give the same provider value twice (randomized encryption doesn't), and it only reached the identifiers that SelectExpression built from type mappings, missing a distinct complex type's properties.
Use the property's own comparer (GetKeyValueComparer()). Column expressions don't carry their property, and it wouldn't help the common case with no comparer configured, which is the repro.
Detect the loop (an identifier that doesn't equal itself on the row it was read from) and throw. That turns the hang into an error but doesn't make the query work.
Tests
New tests in AdHocMiscellaneousQueryRelationalTestBase, each run sync and async on SQL Server (with SQL baselines) and SQLite:
Distinct_complex_type_with_value_converted_reference_type_with_collection and _with_split_collection
Distinct_value_converted_string_with_nondeterministic_write_with_collection: a write converter that doesn't give the same provider value twice
Distinct_primitive_collection_with_collection
Union_value_converted_reference_type_with_collection: a set operation's projected columns as identifiers
Union_entity_with_value_converted_key_with_collection and _with_split_collection: a strongly typed converted entity key as the identifier of a set operation
Final_GroupBy_value_converted_key_read_as_same_value_from_different_database_values: the final GroupBy exception above
Both repro queries above hang on main, and so does a run of the new Union tests. Converted entity keys with Include are also covered by the existing KeysWithConverters suites, which pass on SQL Server and SQLite.
- Grouping terms, a Distinct projection and set-operation columns identify rows on the client by their materialized values,
compared with the type mapping's KeyComparer. Through a value converter, the same database value materializes as a new
instance each time, and the default key comparer of a class without Equals compares by reference; so an identifier never
equalled the one just read from the same row, and the collection shaper kept starting a new parent on that row forever.
- Values of a converted reference type are now compared by their provider values, as the database compared them, using a
comparer composed from the converter's ConvertToProviderExpression and the mapping's ProviderValueComparer, which also works
as an expression for precompiled queries.
- Add tests for a GroupBy over such a key projecting its elements and an aggregate, and for a Distinct over such a column
followed by a collection.
Fixesdotnet#39366
- Comparing identifiers by converting them back to provider values runs the write converter, which the read never did. A
converter needn't give the same provider value twice (randomized encryption doesn't), and then an identifier doesn't equal
even the one read from the same row, so a converted string key that worked before now never finished. A write converter
capturing state also had to be inlined into precompiled queries, which can't generate it.
- Only a converted type whose default comparer ends at object.Equals, compared by reference, is now compared by provider
value; strings, records and anything else with its own equality keep the mapping's key comparer, as before.
- Add a test for a Distinct over a converted string whose write converter isn't deterministic, followed by a collection.
Part of dotnet#39366
- Checking whether a converted type compares by reference looked up its Equals(object) and assumed one was found. An
interface declares none, so the lookup returned null and set operations and groupings over complex types, in a table or
in JSON, failed with a NullReferenceException.
- An interface, or object itself, now keeps the mapping's key comparer, as it did before: what Equals does depends on the
instance, so there is nothing to say it compares by reference.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Comparer selection still leaves object-typed identifiers vulnerable to hangs and can replace valid custom mapping comparers with nonterminating comparisons.
…ings' own comparers
- The default comparer for object compares with ==, not through Equals, so a converted object-typed property was compared
by reference whatever its instances override, and a Distinct over it followed by a collection never finished. object is
now compared by provider value, like any other class compared by reference; interfaces still call Equals on the instance
and keep the mapping's key comparer.
- A mapping that was given its own comparers, such as a primitive collection's structural one, now keeps its key comparer
rather than having it replaced by a comparison through the converter.
- Add tests for a Distinct over a converted object property and over a primitive collection, each followed by a collection.
Part of dotnet#39366
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Two moderate active issues remain: nondeterministic converters on default-comparer reference types and converted reference-type properties within distinct complex projections can still cause non-advancing collection-identifier comparisons.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Use provider comparers for complex distinct projections
This only updates the otherExpressions branch of ApplyDistinct. When the projection is a complex type, the same method still fills typeProjectionValueComparers with each property's GetKeyValueComparer, so a converted reference-type property inside a distinct complex projection remains compared by object identity. A correlated collection over that projection can therefore hit the same non-advancing identifier loop; the complex-property identifier path also needs the provider-value comparer or an explicit regression/limitation.
…em through the converter
Rows are told apart on the client by their identifier values, and the database
told them apart by their provider values. Rather than guessing from a converted
type's Equals and operators whether its comparer compares by reference, and
building a comparer that converts back to the provider value, read a converted
identifier column without its converter and compare it with the mapping's
ProviderValueComparer. This covers every identifier path, including the
columns of a distinct complex type, and never runs a write converter that
needn't be deterministic.
A final GroupBy's key identifier isn't a row's identity but the grouping key,
which LINQ compares as the model value. Reading it as a provider value split
rows whose database values the converter reads as the same value - "1" and
"01" through int.Parse - into separate groupings with the same key. Keep
reading it through the converter; only a collection's identifiers are read as
provider values.
benedict-odonovan
changed the title
Compare converted reference-type identifiers by their provider values
Read converted collection identifiers as provider values
Nov 2, 2026
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
A remaining coverage gap leaves the converted entity-key and set-operation remapping paths insufficiently verified, including relevant sync/async and split-query scenarios.
A set operation's projected columns, and the key of an entity it returns,
become its identifiers; test both with value converters, the latter with a
strongly typed key in single and split queries.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The broad relational identifier-materialization and comparer changes span many query paths and provider-specific mappings, so the focused SQL Server/SQLite coverage is insufficient without wider human validation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #39366
A query whose rows are told apart by a value-converted property of a reference type never returns; one core stays at 100%. Two examples:
Cause.
Distinctprojection, set-operation columns),SelectExpressionuses those columns as identifiers.Tagthrough the converter, and the default key comparer for a class withoutEqualsfalls back to reference equality. So an identifier never equals the one just read from the same row.HasNext = truewithout advancing the reader, which makes the same row the start of the next parent, again and again.Change. A collection's identifiers are now read and compared as the database returned them, the way the database told the rows apart when it grouped or applied
DISTINCT:ProviderValueProjectionBindingExpressionand pairs it with the mapping'sProviderValueComparer. Every other identifier keeps its accessor and comparer, as before.applyConverterflag onCreateGetValueExpression). The node never survives shaper processing, so precompiled queries are unaffected.ApplyDistinct(including the columns of a distinct complex type and the non-key properties of a JSON-owned entity), bothApplyGroupingoverloads, and both set-operation paths. It also covers single and split queries.Final
GroupByis the exception. Its key identifier isn't a row's identity but the LINQ grouping key, which LINQ compares as the model value. So it's still read through the converter and compared with the key comparer. With a converter that reads different database values as the same one ("1"and"01"throughint.Parse), comparing provider values would have produced two groupings with key1. A converted reference type withoutEqualsas a finalGroupBykey gives one grouping per row, as LINQ to Objects does with reference equality, and doesn't hang.Behavior change. This applies to every converted collection identifier, not only reference types that compare by reference: enums and strongly typed IDs are now compared as their provider values too. That gives the same result for any converter that reads each database value as a distinct model value. With one that doesn't, the collection shapes now follow the database. For example, rows with
"1"and"01"in aDistinct()+ correlated collection, or aGroupBywith an element list, come back as two results with model value1. Onmainthey were merged on the client, which mixed aggregates computed per database group: the merged group listed all three posts but itsCount()was 1.Alternatives considered
Equalsoverride,==, interfaces, structural equality) to decide which types compare by reference. It also ran the write converter, which needn't give the same provider value twice (randomized encryption doesn't), and it only reached the identifiers thatSelectExpressionbuilt from type mappings, missing a distinct complex type's properties.GetKeyValueComparer()). Column expressions don't carry their property, and it wouldn't help the common case with no comparer configured, which is the repro.Tests
New tests in
AdHocMiscellaneousQueryRelationalTestBase, each run sync and async on SQL Server (with SQL baselines) and SQLite:GroupBy_value_converted_reference_type_key_with_elements_and_aggregateDistinct_value_converted_reference_type_with_collectionDistinct_value_converted_object_with_collectionDistinct_complex_type_with_value_converted_reference_type_with_collectionand_with_split_collectionDistinct_value_converted_string_with_nondeterministic_write_with_collection: a write converter that doesn't give the same provider value twiceDistinct_primitive_collection_with_collectionUnion_value_converted_reference_type_with_collection: a set operation's projected columns as identifiersUnion_entity_with_value_converted_key_with_collectionand_with_split_collection: a strongly typed converted entity key as the identifier of a set operationFinal_GroupBy_value_converted_key_read_as_same_value_from_different_database_values: the finalGroupByexception aboveBoth repro queries above hang on
main, and so does a run of the newUniontests. Converted entity keys withIncludeare also covered by the existingKeysWithConverterssuites, which pass on SQL Server and SQLite.