Skip to content

Operations on IQueryable after GroupBy.Select #26748

Closed

Description

@OpenSpacesAndPlaces

Where "MyField" and "MyOtherField" are non-nullable integers.

I'm able to create distinct groupings no problem like:
GroupBy(p=> new { MyField = p.MyField, MyOtherField = p.MyOtherField}).Select(p=> p.First())

I'm also able to preorder the data:
OrderBy(p=> p.MyField).GroupBy(p=> new { MyField = p.MyField, MyOtherField = p.MyOtherField}).Select(p=> p.First())


But if I try to Count:
GroupBy(p=> new { MyField = p.MyField, MyOtherField = p.MyOtherField}).Select(p=> p.First()).Count()

Or shape the return data:
GroupBy(p=> new { MyField = p.MyField, MyOtherField = p.MyOtherField}).Select(p=> p.First()).Select(p=>p.MyField)

post Order the data:
GroupBy(p=> new { MyField = p.MyField, MyOtherField = p.MyOtherField}).Select(p=> p.First()).OrderBy(p=> p.MyField)

I get an error like:

System.InvalidOperationException: Nullable object must have a value.
   at System.Nullable`1.get_Value()
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ClientProjectionRemappingExpressionVisitor.Visit(Expression expression)
   at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ClientProjectionRemappingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ApplyProjection(Expression shaperExpression, ResultCardinality resultCardinality, QuerySplittingBehavior querySplittingBehavior)
   at Microsoft.EntityFrameworkCore.Query.Internal.SelectExpressionProjectionApplyingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPostprocessor.Process(Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)

I've seen the error come up in other threads related to Navigation properties, but for the test case, the table has none.

If I avoid the avoid anonymous types (e.g. single column) - everything works fine for something like Count:
GroupBy(p=> p.MyField).Select(p=> p.First()).Count()

Any help appreciated!


EF Core 6
Microsoft.EntityFrameworkCore.SqlServer
.NET 6.0
Win 11
VS 22

Activity

  1. smitpatel commented on Nov 18, 2021

    @smitpatel
    Contributor

    Not a regression since grouping.First didn't work in previous release.
    Queries with OrderBy/Select after grouping+Select throws client eval error for me since we couldn't translate p=> p.MyField Filed #26753

    Count is failing with exception like above.
    Work-around would be do Count after grouping directly as the result will be the same.

  2. smitpatel commented on Nov 18, 2021

    @smitpatel
    Contributor

    Same issue exist for Any. (kind for All also) Any ends up working because the stale projection isn't getting expanded where above error occurs.
    None of this works if it contains a predicate (which All always has) it will run into #26753

  3. added this to the 7.0.0 milestone on Nov 19, 2021
  4. OpenSpacesAndPlaces commented on Nov 19, 2021

    @OpenSpacesAndPlaces
    Author

    @ajcvickers Any chance this could make it into the next minor release or is a big push needed to fix this?

  5. ajcvickers commented on Nov 22, 2021

    @ajcvickers
    Contributor

    @OpenSpacesAndPlaces If by minor release you mean a 6.x minor release, then current plans are for no such releases before 7.0. If you mean a 6.0.x patch release, then we don't typically add new functionality in patch releases.

  6. OpenSpacesAndPlaces commented on Nov 22, 2021

    @OpenSpacesAndPlaces
    Author

    @ajcvickers Ok - I didn't realize there were no minors this cycle - I was reacting to the next major being 11/2022.

    Well then, yeah, it's probably a stretch to say this would be in a patch only cycle since the features section doesn't talk about anonymous support.
    https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#improved-groupby-support

    Thanks for the dialog on this!

  7. SoftCircuits commented on Feb 12, 2022

    @SoftCircuits

    I can work around the same error in the following code:

    var query = DbContext.TripSegments
        .Where(ts => ts.RailcarTrip.WaybillRailcar.Waybill.CompanyCode == companyCode &&
            ts.IsLoaded && ts.EndDate == null &&
            ts.DestinationCity == city && ts.DestinationState == state);
    
    query = query
        .GroupBy(ts => ts.RailcarTrip.WaybillRailcar.RailcarNumber)
        .Select(x => x.OrderByDescending(ts => ts.RailcarTrip.StartDate).First());
    
    int count = await query.CountAsync();

    By using Count() directly (as suggested above).

    int count = await query.GroupBy(ts => ts.RailcarTrip.WaybillRailcar.RailcarNumber).CountAsync();

    But is there a workaround that allows me to add a final SELECT clause?

    var query = DbContext.TripSegments
        .Where(ts => ts.RailcarTrip.WaybillRailcar.Waybill.CompanyCode == companyCode &&
            ts.IsLoaded && ts.EndDate == null &&
            ts.DestinationCity == city && ts.DestinationState == state);
    
    query = query
        .GroupBy(ts => ts.RailcarTrip.WaybillRailcar.RailcarNumber)
        .Select(x => x.First());
    
    var results = query.Select(ts => new MyType()
    {
        // ...
    });

    The entire point of the GroupBy() is to remove the older of any duplicate RailcarNumbers. I don't think there's another way to do this.

  8. OpenSpacesAndPlaces commented on Feb 13, 2022

    @OpenSpacesAndPlaces
    Author
  9. SoftCircuits commented on Feb 13, 2022

    @SoftCircuits

    If you can skip the projection into a new type at the end it should work. At least in our travels, projecting or layering too much over the group by will cause this.

    Thanks, that didn't seem to be an option for me because the SELECT clause uses a lot of navigation properties to get the data I need.

    However, I appear to have it working by actually doing the projection before the GROUPBY. And then grouping the results of that. To be honest, I was a little surprised this worked.

    Other thing I will note, unless you're paging results, there isn't going to be a huge difference for client siding most things unless your column and/or row count is massive.

    Yes, especially in my case as there were very few duplicates. But removing anything on the client side would definitely mess up my paging.

  10. 17 remaining items

  11. regisbsb commented on Apr 23, 2025

    @regisbsb

    For future me and others:
    to work around this you need to join instead of group by:

    var statementsQueryable = _dbContext.Statements.AsQueryable();
    
    var latestVersions = _dbContext.Statements
        .GroupBy(e => e.Key)
        .Select(g => new
        {
            g.Key,
            Version = g.Max(e => e.Version)
        });
    
    statementsQueryable = statementsQueryable
        .Join(latestVersions,
            statement => new { statement.Key, statement.Version },
            latest => latest,
            (statement, latest) => statement);
    

    then you can do all operations without worry

  12. added theissue type on Jun 15, 2025
  13. jnavarrete777 commented on Jul 16, 2025

    @jnavarrete777
  14. roji commented on Jul 16, 2025

    @roji
  15. modified the milestones: Backlog, 11.0.0 on Jun 16, 2026
  16. added a commit that references this issue on Jun 17, 2026
    3ae41e9
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions