问题
Currently testing with EF Core version 3.1.1.
When I search, I find references to this problem, but I don't see any definitive answers about why this happens, and whether it is a bug that will be fixed or if it's expected behavior. This is just as simple as it looks--the BatchRequest table/entity has an integer column/property called BatchId:
var batchRequestGroups = context.BatchRequests.GroupBy(br => br.BatchId).ToList();
When I run this, I get a System.InvalidOperationException, "Client side GroupBy is not supported."
So, based on the explanations that I find online, it appears that EF Core 3.x will no longer allow client-side GroupBys except in the top-level projection.
From https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#linq-queries-are-no-longer-evaluated-on-the-client:
Old behavior
Before 3.0, when EF Core couldn't convert an expression that was part of a query to either SQL or a parameter, it automatically evaluated the expression on the client. By default, client evaluation of potentially expensive expressions only triggered a warning.
New behavior
Starting with 3.0, EF Core only allows expressions in the top-level projection (the last Select() call in the query) to be evaluated on the client. When expressions in any other part of the query can't be converted to either SQL or a parameter, an exception is thrown.
Does this mean that in previous versions, ALL GroupBy clauses were evaluated on the client?
Also, why can't the GroupBy in my example be evaluated in SQL? And how is my example's GroupBy not the top-level projection?
Again, my main question: is this a bug or expected behavior?
回答1:
Starting from EF 3.0 clientside evaluations of queries are treated as an error, unlike the previous versions where it was treated as a warning.
Does this mean that in previous versions, ALL GroupBy clauses were evaluated on the client?
NO. Not all of the group by statements were being evaluated on clientside. It depends on whether the EF core was able to translate the LINQ to a supported SQL statement.
Also, why can't the GroupBy in my example be evaluated in SQL? And how is my example's GroupBy not the top-level projection?
My guess is your entity contains other relationships and EF core loading and grouping by specified property which can't be done in SQL.
Again, my main question: is this a bug or expected behavior?
It's not a bug apparently. This expected behaviour.
来源:https://stackoverflow.com/questions/60213529/simplest-group-by-fails-in-ef-3-x-with-client-side-groupby-is-not-supported