Query with GroupBy or GroupJoin throws exception
If you run into issue with GroupBy/GroupJoin and arrive here, then please take time to read https://github.com/dotnet/efcore/issues/17068#issuecomment-586464350 fully to direct your feedback in specific issue for your specific scenario.
Read our documentation about this here
Group By
Linq GroupBy operator allows to create IGrouping<TKey, TElement> where TKey & TElement could be arbitrary types. Further, IGrouping implements IEnumerable<TElement> which means you can compose over using any queryable operator after grouping.
In contrast SQL GROUP BY keyword is very restrictive. In SQL, you can only use scalar values in GROUP BY. Most database also allows only referencing grouping key columns or aggregate applied over any other column. Hence selecting a column which is not in key or does not have aggregate applied is not possible.
Due to this mismatch, not all linq GroupBy can be translated to SQL GROUP BY. In EF Core 3.0 we have support for SQL GROUP BY but not for all linq GroupBy. There are few bugs/limitation in this translation for which we have various issues filed, mainly for scenarios where Distinct or a predicate is applied before aggregate operation.
Another GroupBy scenario which can be translated to server is selecting first element of each group which is being tracked by #13805
Most other linq GroupBy cannot be evaluated on server and must be evaluated on client side. This issue tracks about allowing EF Core to do this client side grouping implicitly. Absence of this feature means users would have to manually call AsEnumerable before GroupBy to explicitly falling into client side grouping.
GroupJoin
Linq GroupJoin is a queryable operator which does not have equivalent SQL keyword. The biggest use of GroupJoin for an ORM is to generate Left join on server side as mentioned here. Customers.GroupJoin(Orders,...) would create IEnumerable<Order> for each Customer. As with GroupBy, you can compose over this in Linq but there is no translation. Again, GroupJoin requires client side grouping to generate correct result. This issue also tracks adding implicit support for it.
In recent discussion it came up that, allowing this may be pit of failure (with escape hatch at the bottom :trollface: ).
https://github.com/aspnet/EntityFrameworkCore/issues/12560#issuecomment-525084333 is a good example of why it's dangerous to implement implicit client evaluation of GroupBy. Requiring users to do explicit client evaluation with AsEnumerable forces them to think and understand the distinctions and perf impact, etc.
Reiterating previous thoughts, the more I think of it, the more I think we should aim to avoid implicit client evaluation for any scenario where client evaluation is (significantly) more expensive than server evaluation, when possible.
In retrospect it actually seems like quite a mistake for LINQ to have GroupBy returning groupings rather than a reduced/aggregated scalar, given that it tends to follow SQL in operator naming and the general prevalence of SQL.
Linking all other bugs from backlog which requires client side GroupBy. If we decide to fix this, then please consider all the scenarios in linked closed bugs.
If we decide to close this, also close related issues which are blocked on this one. And also clean up tests in codebase.
~This may have some value in doing because of #17944~ Work-around is simpler than thought due to just doing collection projection.
I have updated the title & description of this issue so it becomes easier to find and we can point users to this when they run into issues with GroupBy/GroupJoin.
Is this article related to the topic? If so, maybe it makes sense to clean up and stop confusing people
Closing this as by-design because there is no reasonable or valuable translation to the server we can do in these cases.
What's the difference between collection navigation property and GroupJoin? Why using the former is translated and the latter is not ("by design"?!)
And yet LINQ to SQL has no problem translating cases LINQ to EF Core 3 fails miserably at.
@NetMage - Feel free to use LINQ to SQL for scenarios where you find it useful.
Just to add some context to people hitting this and to add to what @smitpatel and @ajcvickers wrote above.
When there's a way to fully translate a LINQ construct to SQL, we definitely do so (or at least strive to do so, leaving issues open to track). However, in many cases that is simply not possible, as @smitpatel explained at the top of this issue. If anyone thinks we should be able to translate a LINQ construct to SQL but do not, please open a new issue with the LINQ construct and the proposed SQL translation you'd like to see.
In cases where we can't translate to SQL, since version 3.0 we only perform implicit client evaluation in very restricted cases - when we can be (almost) sure that there will be no big performance degradation due to unintentionally fetching huge amounts of data from the server. We are careful with this since it has caused problems in the past, and we want to keep the line dividing server (SQL) evaluation and client evaluation as crystal-clear as possible. However, if what you're looking for is client evaluation, simply add AsEnumerable at any point in your LINQ query, and anything coming after that will be performed client-side. This allows you to use any complex construct - GroupJoin, GroupBy, anything - as long as you're aware you'll be pulling all the necessary data back from the database.
This issue tracks about allowing EF Core to do this client side grouping implicitly. Absence of this feature means users would have to manually call AsEnumerable before GroupBy to explicitly falling into client side grouping.
@ajcvickers would like to re-discuss this
@smitpatel Is LINQ to SQL a supported feature? Is it under active development? Would you recommend it for new projects? Or was that statement like recommending SilverLight or LightSwitch?
To be clear, I am all for the removal of automatic client side processing in EF Core 3.x and the requirement for manually requesting it when desired with AsEnumerable, but this is the second time the latest version of EF has lost the capability to translate queries to SQL that were present in much older technologies. I like the suggestion to open specific translation issues and will work on that.
[...] the latest version of EF has lost the capability to translate queries to SQL that were present in much older technologies.
I understand (and even identify) with the frustration around this. It's worth reminding that EF Core is a separate product from both LINQ to SQL and Entity Framework 6, and we generally don't commit to supporting everything that was supported in these products; this frees EF Core to do things right and make, rather than being bound by legacy features etc. This is of course not good news for someone looking to migrate from LINQ to SQL to EF Core, but unfortunately that's the way things are.
As I wrote above, where there's a reasonable, performant SQL translation for a LINQ construct, we in general strive to implement it regardless of whether they were supported or not in older technologies (provided the effort involved justifies the value, depending on competing priorities, etc. etc.). On the other hand, for implicit/automatic client evaluation of GroupBy, a conscious, reasoned decision was made to not support that, because we believe that requiring explicit client evaluation would be better for our users - even if LINQ to SQL did do this.
However, we'll be rediscussing the GroupBy decision specifically (which is why this issue was reopened).
It was working in aspnetcore 2.2. Now it stopped working. And 3.1x is a a LTS, making us either have to downgrade to 2.1, or force a lot of code change in 3.1. This is a decision that not well made. Please at least give an option to change it to old behavior.
@xqiu unless I'm mistaken, this was client-evaluating in 2.2, not translating to SQL. You can achieve that exact same behavior with 3.x by putting AsEnumerable before your GroupBy - that will trigger client evaluation (see this breaking change note). We no longer do this implicitly in 3.x in order to protect people from unknowingly pulling in large amounts of data from the database because your specific GroupBy can't be translated to SQL.
We all agree that removing the client evaluation is a good thing in general.
The problem though is that there is no easy way to switch the query context. AsEnumerable() changes the type to IEnumerable<T>, hence the final materialization Async calls are no more available. ToList() / await ToListAsync() immediately executes the query at that point. And AsAsyncEnumerable() requires installing additional package for further LINQ support.
But let me get back to my previous comment. Let forget about GroupBy for now and discuss the GroupJoin. While it has no full server side support, the translation and cooperative client/server evaluation is supported for queries using collection navigation properties. e.g. query like
var query = db.Set<Foo>()
.Select(foo => new
{
foo.Id,
foo.Name,
Bars = foo.Bars
.Select(bar => new
{
bar.Id,
bar.Name
}).ToList()
};
is supported, but the equivalent
var query = db.Set<Foo>()
.GroupJoin(db.Set<Bar>(), foo => foo.Id, bar => bar.FooId, (foo, fooBars) => new
{
foo.Id,
foo.Name,
Bars = fooBars
.Select(bar => new
{
bar.Id,
bar.Name
}).ToList()
};
is not.
This makes no sense to me. While in StackOverflow we always tell people to use navigation properties, many times they just don't want to add navigation properties to their models (for some unknown reason), or just can't if there is no FK relationship between the joining tables. The fact that it is supported for navigation properties means that it should be supported for GroupJoins.
If this scenario is not targeted by this issue and the current inability to translate such queries is just a current limitation that will be addressed in the future, that's fine. Just wanted to make sure it is not considered "by design" and "won't fix".
Perhaps what would help is AsEnumerableAsync, though I am not sure what it would return...
@powermetal63 here's one good justification (at least IMHO) for why the 1st is supported and the 2nd isn't... The main point of removing implicit client evaluation between 2.2 and 3.0 is to make it extremely clear/explicit which parts of the query are executed on the server, and which on the client. Our current logic is extremely simple: everything except the top-level select must always be server-evaluatable, or we throw. If we start to add other exceptions - such as GroupJoin - we start muddying things up again, and users have to start remembering what's implicitly client-evaluatable, and what's not. In other words, a user could write a GroupJoin - expecting it to be server-translated and efficient - not knowing that in fact all data is being brought back from the server, etc. (this is important especially if we continue to compose operators over the GroupJoin results). With the current situation there's just one, crystal-clear case where we implicitly client-evaluate, and that's an advantage IMHO.
And as always, it's extremely easy to insert an AsEnumerable before the GroupJoin to explicitly trigger client evaluation, so implicit evaluation of GroupJoin seems to me to have very limited value. Having said that, this is only my opinion and the team does intend to rediscuss our strategy with regards to client evaluation and possibly relax our current restrictions.
@NetMage AsEnumerableAsync is provided by EF Core, returning an IAsyncEnumerable. You can use foreach to iterate over that, or compose over it with async LINQ operators from the System.Linq.Async package.
@roji The only difference between the two queries I see is that for the first one somewhere in the pipeline the translator seems to be replacing (expanding?) collection navigation property with GroupJoin. And I believe the supported query does not bring all the data to client - there are no Includes for related data, the projection should be happening server side and somehow the resulting query shape is materialized on the client. So IMHO it works exactly as one would expect.