Skip to content

No items when projecting out groupings with a null key #32026

Closed

Description

@NiJeTi

Hello!

I have a code which I expect to return me 3 groups of items.

var spec = new EntitySpec();
var query = _repository.GetQuery(spec);

var result = await query
    .GroupBy(x => (Guid?)x.Json.RootElement.GetProperty(property).GetGuid())
    .Select(g => new { g.Key, Count = g.Count(), Items = g.ToList() })
    .ToListAsync(cancellationToken);

It really returns me groups, but unfortunately the result is incomplete:

[
    {
        "key": "d0005e8f-ebaa-481d-aabf-628b5d172c05",
        "count": 2,
        "items": [
            "<item1>",
            "<item2>"
        ]
    },
    {
        "key": "f6223371-aa16-4e51-94c7-f91af84b2200",
        "count": 1,
        "items": [
            "<item3>"
        ]
    },
    {
        "key": null,
        "count": 2,
        "items": []
    }
]

All the expected groups and their sizes are here, but for the last one with null key there are no items returned.

If I make a direct request to database it returns me expected data.

select count(*), "Json"::jsonb -> 'c41c88f5-fb3b-4b77-bc11-2df17e6312b9' as "keys"
from "Entities"
group by "Json"::jsonb -> 'c41c88f5-fb3b-4b77-bc11-2df17e6312b9'

image

Provider and version information

EF Core version: 7.0.8
Database provider: Npgsql.EntityFrameworkCore.PostgreSQL
Target framework: .NET 6.0
Operating system: Any
IDE: Any

Activity

  1. roji commented on Oct 11, 2023

    @roji
    Member

    This issue is lacking enough information for us to be able to fully understand what is happening. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

  2. NiJeTi commented on Oct 13, 2023

    @NiJeTi
    Author

    Hello again! As you requested I've created a sample application. You can find it here -> https://github.com/NiJeTi/ef-json.

    Described problem is still here despite I've used the most recent versions of .NET, EF Core libraries and PostgreSQL database.

    image

  3. ajcvickers commented on Oct 15, 2023

    @ajcvickers
    Contributor

    @roji Looks like this is specific to PostgreSQL mapping of a JsonDocument property.

  4. NiJeTi commented on Oct 17, 2023

    @NiJeTi
    Author

    @roji Looks like this is specific to PostgreSQL mapping of a JsonDocument property.

    Should I create a copy of this issue to respective PorstreSQL repository then?

  5. roji commented on Oct 18, 2023

    @roji
    Member

    @NiJeTi I'll hopefully get around to investigating this soon (lots on my plate at the moment), no need to open another issue until we confirm what exactly it's about.

  6. ajcvickers commented on Jan 5, 2024

    @ajcvickers
    Contributor

    @roji Confirmed this still repros on 8.0. See code and output below. Looks to me like AS t1 ON t0."Key" = t1."Key" is wrong when the key is nullable because null won't match null.

    var jsonId = Guid.Empty;
    using (var db = new DatabaseContext())
    {
        await FillDatabase(db);
    }
    
    using (var db = new DatabaseContext())
    {
        var results = await db
            .Set<Entity>()
            .GroupBy(x => (Guid?)x.Json.RootElement.GetProperty(jsonId.ToString()).GetGuid())
            .Select(g => new { g.Key, Count = g.Count(), Items = g.ToList() })
            .ToListAsync();
    
        foreach (var grouping in results)
        {
            Console.WriteLine($"  Key: {grouping.Key} Count: {grouping.Count}");
            foreach (var item in grouping.Items)
            {
                Console.WriteLine($"    {item.Json}");
            }
        }
    }
    
    async Task FillDatabase(DatabaseContext db)
    {
        await db.Database.EnsureDeletedAsync();
        await db.Database.EnsureCreatedAsync();
    
        jsonId = Guid.NewGuid();
        
        for (var i = 0; i < 3; i++)
        {
            var json = new Dictionary<Guid, Guid?>
            {
                [jsonId] = i == 0 ? null : Guid.NewGuid()
            };
            var entity = new Entity
            {
                Json = JsonSerializer.SerializeToDocument(json)
            };
            db.Add(entity);
        }
    
        await db.SaveChangesAsync();
    }
    
    internal sealed class Entity
    {
        public Guid Id { get; set; }
        public required JsonDocument Json { get; set; }
    }
    
    internal sealed class DatabaseContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"server=localhost;user id=postgres;password=;database=One")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity>();
        }
    }
    info: 1/5/2024 11:02:58.594 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command) 
          Executed DbCommand (4ms) [Parameters=[@__ToString_0='cb63d7d2-813f-4642-aa91-760a8f5bd1c3'], CommandType='Text', CommandTimeout='30']
          SELECT t0."Key", t0.c, t1."Id", t1."Json"
          FROM (
              SELECT t."Key", count(*)::int AS c
              FROM (
                  SELECT CAST(e."Json" ->> @__ToString_0 AS uuid) AS "Key"
                  FROM "Entity" AS e
              ) AS t
              GROUP BY t."Key"
          ) AS t0
          LEFT JOIN (
              SELECT e0."Id", e0."Json", CAST(e0."Json" ->> @__ToString_0 AS uuid) AS "Key"
              FROM "Entity" AS e0
          ) AS t1 ON t0."Key" = t1."Key"
          ORDER BY t0."Key"
      Key: 2347b859-c150-4ebf-b887-30d94f2f232f Count: 1
        System.Text.Json.JsonDocument
      Key: 4588a331-9cd7-40f5-b5c3-f2b25b22ce5c Count: 1
        System.Text.Json.JsonDocument
      Key:  Count: 1
    
  7. roji commented on Jan 5, 2024

    @roji
    Member

    @ajcvickers could you see this failing with SQL Server too? It doesn't look like it should be PG-specific...

  8. ajcvickers commented on Jan 5, 2024

    @ajcvickers
    Contributor

    @roji I didn't try SQL Server because of the JsonDocument property mapping. You don't think that's relevant here?

  9. roji commented on Jan 5, 2024

    @roji
    Member

    Sorry, you're probably right. I'll have to investigate to see if this is really an Npgsql issue or something being triggered on the EF side - assigning to myself for investigation.

  10. self-assigned this
    on Jan 5, 2024
  11. roji commented on Jan 10, 2024

    @roji
    Member

    Finally investigated this (sorry it took so long).

    This isn't PG-specific or related to JsonDocument - here's the same thing failing on SQL Server with GroupBy over a simple nullable column:

    await using var ctx = new DatabaseContext();
    await ctx.Database.EnsureDeletedAsync();
    await ctx.Database.EnsureCreatedAsync();
    
    ctx.Entities.AddRange(
        new() { Key = "hello" },
        new() { Key = null });
    await ctx.SaveChangesAsync();
    
    var results = await ctx
        .Set<Entity>()
        .GroupBy(e => e.Key)
        .Select(g => new { g.Key, Count = g.Count(), Items = g.ToList() })
        .ToListAsync();
    
     foreach (var grouping in results)
     {
         Console.WriteLine($"  Key: {grouping.Key ?? "<null>"} Count: {grouping.Count}");
         foreach (var item in grouping.Items)
         {
             Console.WriteLine($"    ID: {item.Id}, Key: {item.Key}");
         }
     }
    
    public class DatabaseContext : DbContext
    {
        public DbSet<Entity> Entities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Entity
    {
        public int Id { get; set; }
        public string? Key { get; set; }
    }

    The SQL this produces:

    SELECT [t].[Key], [t].[c], [e0].[Id], [e0].[Key]
    FROM (
        SELECT [e].[Key], COUNT(*) AS [c]
        FROM [Entities] AS [e]
        GROUP BY [e].[Key]
    ) AS [t]
    LEFT JOIN [Entities] AS [e0] ON [t].[Key] = [e0].[Key]
    ORDER BY [t].[Key]

    Note that in order to get the items for each group, we're doing a LEFT JOIN back on the Entities table, with the Key being the join predicate. However, we're using simple equality, so when the Key is null, we get no results. In other words, we're missing null semantics on the join predicate in this case.

    I'm not sure whether this is a GroupBy-specific bug - It's worth checking what happens with other joins that aren't produced via GroupBy; i.e. when the user expresses a join in LINQ referencing a nullable join key, do we consistently apply null semantics onto that?

  12. changed the title [-]Cannot retrieve grouped items[/-] [+]No items when projecting out groupings with a null key[/+] on Jan 10, 2024
  13. 2 remaining items

  14. assigned and unassigned on Jan 11, 2024
  15. added this to the Backlog milestone on Jan 11, 2024
  16. ajcvickers commented on Jan 11, 2024

    @ajcvickers
    Contributor

    @maumar Assigned this to you as a null compensation issue. Specifically, [t].[Key] = [e0].[Key] should have the additional logic to match null to null.

  17. added theissue type on Jun 15, 2025
  18. benedict-odonovan commented on Oct 22, 2026

    @benedict-odonovan
    Contributor

    I looked into this, and it isn't specific to GroupBy. Any correlated collection whose Where compares two nullable values loses its null matches. It still reproduces on current main and on release/11.0 on SQL Server and SQLite.

    // Each post with the ids of the posts in the same category. Category is a nullable string; posts 3 and 4 have none.
    var query = context.Posts.Select(p => new
    {
        p.Id,
        SameCategory = context.Posts.Where(q => q.Category == p.Category).Select(q => q.Id).ToList()
    });
    SELECT [p].[Category], [p].[Id], [p0].[Id]
    FROM [Posts] AS [p]
    LEFT JOIN [Posts] AS [p0] ON [p].[Category] = [p0].[Category]
    ORDER BY [p].[Id]
    Id = 1, SameCategory = [1, 2]
    Id = 2, SameCategory = [1, 2]
    Id = 3, SameCategory = []        <- expected [3, 4]
    Id = 4, SameCategory = []        <- expected [3, 4]
    

    The same correlation inside an aggregate does treat null as equal to null, because it stays a subquery with a WHERE:

    var counts = context.Posts.Select(p => new { p.Id, Count = context.Posts.Count(q => q.Category == p.Category) });
    SELECT [p].[Id], (
        SELECT COUNT(*)
        FROM [Posts] AS [p0]
        WHERE [p0].[Category] = [p].[Category] OR ([p0].[Category] IS NULL AND [p].[Category] IS NULL)) AS [Count]
    FROM [Posts] AS [p]

    This returns Count = 2 for posts 3 and 4. So ToList() and Count() over the same Where disagree about which rows match.

  19. added a commit that references this issue on Oct 22, 2026
    079c5b9
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