Skip to content

Query never returns (infinite loop on the client) when grouping by a value-converted reference type and projecting the group's elements #39366

Closed

Description

@benedict-odonovan

Bug description

Grouping by a property whose CLR type is a class with a value converter, and projecting the grouping's elements, hangs. ToList()/ToListAsync() never returns, and one core stays at 100% CPU. The SQL itself is fine and returns promptly; the loop is in the client-side materialization of the correlated collection.

What I narrowed it down to:

  • It happens with the GROUP BY + LEFT JOIN translation of a projection that combines the elements with an aggregate (repro below). On release/11.0 it also happens with the elements alone, Select(g => new { g.Key, Ids = g.Select(p => p.Id).ToList() }). On main, that elements-only shape is translated as a single scan since Stream GroupBy elements instead of joining the source back to itself #38963, and it works.
  • It doesn't depend on null keys, duplicate keys, or the aggregate. It happens with every row non-null and every key unique.
  • A ValueComparer passed to HasConversion(..., valueComparer) doesn't help.
  • Overriding Equals/GetHashCode on the CLR type does fix it.
  • A value-type converted key, such as an enum stored as a string, works fine.
  • Grouping by an entity whose type has such a property also hung in my testing (GroupBy(o => o.Blog).Select(g => new { g.Key, Ids = ..., Count = g.Count() })). That entity type also had owned types, and I didn't reduce that case further.
  • It isn't specific to GroupBy. Distinct over such a column, followed by a collection, hangs the same way on main:
    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() }).

Your code

using Microsoft.EntityFrameworkCore;

await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Posts.AddRange(
    new Post { Id = 1, Tag = new Tag { Name = "efcore" } },
    new Post { Id = 2, Tag = new Tag { Name = "efcore" } },
    new Post { Id = 3, Tag = new Tag { Name = "linq" } });
await context.SaveChangesAsync();

var query = context.Posts
    .GroupBy(p => p.Tag)
    .Select(g => new { g.Key, Ids = g.Select(p => p.Id).ToList(), Count = g.Count() });

Console.WriteLine(query.ToQueryString());

// Never returns; one core stays at 100%.
foreach (var group in await query.ToListAsync())
{
    Console.WriteLine($"Key = {group.Key.Name}, Ids = [{string.Join(", ", group.Ids)}], Count = {group.Count}");
}

public class BlogContext : DbContext
{
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=ConvertedKeyHangRepro;Trusted_Connection=True;TrustServerCertificate=True");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>().Property(p => p.Id).ValueGeneratedNever();
        modelBuilder.Entity<Post>().Property(p => p.Tag).HasConversion(t => t.Name, n => new Tag { Name = n });
    }
}

public class Post
{
    public int Id { get; set; }
    public Tag Tag { get; set; }
}

// A plain class, without Equals/GetHashCode overrides.
public class Tag
{
    public string Name { get; set; }
}

The SQL is printed and then nothing else:

SELECT [p1].[Tag], [p0].[Id], [p1].[c]
FROM (
    SELECT [p].[Tag], COUNT(*) AS [c]
    FROM [Posts] AS [p]
    GROUP BY [p].[Tag]
) AS [p1]
LEFT JOIN [Posts] AS [p0] ON [p1].[Tag] = [p0].[Tag]
ORDER BY [p1].[Tag]

Expected:

Key = efcore, Ids = [1, 2], Count = 2
Key = linq, Ids = [3], Count = 1

The same hang happens with UseSqlite("Data Source=repro.db"). Adding public override bool Equals(object obj) => obj is Tag t && t.Name == Name; and a matching GetHashCode to Tag makes the query return the expected output.

Stack traces

No exception; the query never completes. Hot frames from a dotnet-trace CPU sample of the spinning process:

  dynamicClass.lambda_method…              (compiled shaper)
  DynamicMethod.CreateDelegate(Type, Object)
  BufferedDataReader.IsDBNull(int32)
  ConcurrencyDetector.EnterCriticalSection()

Verbose output


EF Core version

release/11.0

Database provider

No response

Target framework

No response

Operating system

No response

IDE

No response

Activity

  1. added this to the 12.0-preview1 milestone on Oct 22, 2026
  2. added theissue type on Oct 22, 2026
  3. added 3 commits that reference this issue on Oct 24, 2026
    80bb360
    07849a1
    a796669
  4. added a commit that references this issue on Nov 3, 2026
    2c70cea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions