Skip to content

Aggregate a column into a value set in a GroupBy projection (array_agg) #96

Open

Description

@CaffeinatedCoder

array_agg(anynonarray) → anyarray is the way PostgreSQL builds an array from rows, and the natural LINQ for it is a GroupBy projection that ends in a set:

orders.GroupBy(o => o.CustomerId)
      .Select(g => new { g.Key, Tags = StringSet.From(g.Select(o => o.Tag)) })

In memory StringSet.From(IEnumerable<string>) exists for every family; in a query nothing translates it, so EF either client-evaluates the whole group (projection) or throws (predicate). range_agg has had its translation since 9.0.0; this is the value-set counterpart.

Verified live: select array_agg(x) from unnest(array[2,1,2]) x → {2,1,2} (not canonical); array_agg(distinct x order by x) → {1,2}, but ORDER BY on text is the collation's order, not ordinal, so it cannot be used to canonicalise a string set on the server (the same reason array_sort is refused).

Proposed API: IEnumerable<T>.ToStringSet(), ToInt32Set(), … (one per family, like the ToRangeSet() bridges), plus recognising XSet.From(IEnumerable) in a projection.

Translation: array_agg(o."Tag") with the set's type mapping on the result. The result is not canonical until it is materialised, which is exactly the situation array_cat is in, so the aggregate must emit under the same ValueSetSqlGuard rules: allowed in the outermost projection (materialisation canonicalises), under @>/<@/&&, cardinality(…) = 0 and a null test; refused under equality, Count, GROUP BY, DISTINCT, ORDER BY and ExecuteUpdate. array_agg of zero rows is NULL, which must read as the empty set (COALESCE(array_agg(…), '{}')) or be documented, as range_agg is (E07).

Done when: the aggregate translates for every family, the guard refuses the same compositions it refuses for array_cat (seeded), and a live test agrees with memory, including the zero-row group.

Found by the PostgreSQL catalogue sweep (pg_proc over anyarray), 2026-10-17.

Activity

  1. added
    enhancement
    area/value-sets
    package/efcore
    package/core
    on Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/value-setsenhancementpackage/corepackage/efcore

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions