Skip to content

Analyzer warning and quick fix for ToDictionary over GroupBy #16838

Description

@roji

We've had discussions in #16730 and offline about the following:

var test = await this.dbcontext.MyEntity
        .GroupBy(x => x.Status)
        .ToDictionary(x => x.Key.Name, y => y.Count());

There is evidence to support that a common expectation is for this to get translated for server evaluation. However, since ToDictionary() is only defined over IEnumerable, EF Core cannot see the aggregate function and the grouping will in fact be performed client-side.

We can have an analyzer to detect this, and even suggest a quick fix of extracting the aggregate lambda inserting a Select() with it between the GroupBy and ToDictionary.

Activity

  1. divega commented on Jul 31, 2019

    @divega
    Contributor

    The analyzer should probably recognize ToLookup as well.

  2. added this to the Backlog milestone on Aug 5, 2019
  3. removed this from the Backlog milestone on Nov 20, 2019
  4. molinch commented on Aug 5, 2024

    @molinch

    I would love to see such an analyzer, we just fell into this trap and it was a pain to diagnose. Especially for ToDictionaryAsync since it comes from EF.Core.

  5. roji commented on Aug 5, 2024

    @roji
    MemberAuthor

    Reopening to reconsider doing this, now that we're starting to have static analysis capabilities for EF LINQ queries (via precompiled queries).

  6. reopened this on Aug 5, 2024
  7. added this to the Backlog milestone on Aug 5, 2024
  8. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions