Repository navigation
Description
Updated as of 3/14/2018 based on implementation introduced
LINQ's GroupBy() operators can sometimes be translated to SQL's GROUP BY clauses, in particular when aggregate functions are applied in the projection.
Scope for 2.1 release
Our current intention is for the scope of the work in 2.1 to improve how LINQ's GroupBy is evaluated in this particular scenario:
Grouping on a simple expression that references a single column or multiple columns (using an anonymous type) of the query root and then projecting any aggregate operation from (Count, Sum, Average, Min, Max) and/or any individual property that is part of the grouping key (this will be translated to GROUP BY in SQL)
What is supported in 2.1.0-preview2
Apart from what is supported in 2.1.0-preview1 (details below), we have also added some more patterns
- Grouping by constant/variables
- Grouping by properties of reference navigations
- Ordering or filtering on grouping key or aggregate
- Aggregate being DTO/nominal type
Examples
// Grouping by constant or a variable from closure
db.Orders.GroupBy(o => 2).Select(g => g.Count());
var a = 5;
db.Orders.GroupBy(o => a).Select(g => g.Count());
// Grouping by scalar properties from reference navigations
db.Orders.GroupBy(o => o.Customer.City).Select(g => g.Count());
// Ordering by Key/Aggregate after GroupBy
db.Orders.GroupBy(o => o.CustomerID).OrderBy(o => o.Count()).Select(g => new { g.Key, Count = g.Count() });
// Filtering on Key/Aggregate after GroupBy (Translates to Having clause in SQL)
db.Orders.GroupBy(o => o.CustomerID).Where(o => o.Count() > 0).Select(g => new { g.Key, Count = g.Count() });
// Projecting aggregate into nominal type
db.Orders.GroupBy(o => o.CustomerID).Select(g => new CustomerCountInfo { g.Key, Count = g.Count() });And a few bugfixes - #11218 #11157 #11176
What is supported in 2.1.0-preview1
// Grouping by single column projecting aggregate or key
db.Orders.GroupBy(o => o.CustomerId).Select(g => g.Count());
db.Orders.GroupBy(o => o.CustomerId).Select(g => new { CustomerId = g.Key, Count = g.Count() });
// Grouping by multiple columns (using anonymous type) projecting aggregate or key or nested key
db.Orders.GroupBy(o => new { o.CustomerId, o.OrderDate }).Select(g => g.Sum(o => o.Cost));
db.Orders.GroupBy(o => new { o.CustomerId, o.OrderDate })
.Select(g => new { CustomerId = g.Key.CustomerId, Sum = g.Sum(o => o.Cost) });
db.Orders.GroupBy(o => new { o.CustomerId, o.OrderDate })
.Select(g => new { Key = g.Key, Sum = g.Sum(o => o.Cost) }); // Where Key will be anonymous object
// Grouping after complex query root
(from o in db.Orders.Where(o => o.OrderID < 10400).OrderBy(o => o.OrderDate).Take(100)
join c in db.Customers.Where(c => c.CustomerID != "DRACD" && c.CustomerID != "FOLKO").OrderBy(c => c.City).Skip(10).Take(50)
on o.CustomerID equals c.CustomerID
group o by c.CustomerID)
.Select(g => new { g.Key, Count = g.Average(o => o.OrderID) });
db.Orders.OrderBy(o => o.OrderID)
.Skip(80)
.Take(500)
.GroupBy(o => o.CustomerID)
.Select(g => g.Max(o => o.OrderID));
// All above examples have group of entity types after GroupBy
// Selecting Group of anonymous types containing multiple columns
db.Orders.GroupBy(o => o.CustomerId, new {o.OrderDate, o.Price}).Select(g => g.Sum(t => t.Price));Scenarios that we are not planning to improve in the 2.1 release
1. Grouping on constants (available in 2.1.0-preview2)
2. Grouping on an entity (e.g. a reference navigation property)
3. Projecting non-aggregate scalar subqueries after grouping, e.g. FirstOrDefault()
4. Making groups of multiple entityTypes using anonymous types.
5. Using Key/Aggregate values after GroupBy in joins (#10012)
All the scenarios above present different variations depending on what happens after the GroupBy, e.g. is there an aggregate function or not, is the key mentioned in the projection or not, etc. These scenarios will still result in client evaluation.
We would appreciate if customers that care about EF Core supporting any of those scenarios that are scoped out from 2.1 to create individual issues for them, up-vote them, and keep the discussion there.
Activity
alexvaluyskiy commentedon Jul 14, 2015
I have these classes
If I use this code
EF7 generates this SQL
without grouping and projection and groups data on the client side
If I use Group by with Inner Join with this code
I get this error
EF 7.0.0-beta6-13735
rowanmiller commentedon Jul 24, 2015
Consider these cases when translating SQL
leus commentedon Oct 2, 2015
Just another test case:
Throws the following exception:
This is for a recursive tree-like structure. Here I'm just trying to count children.
rowanmiller commentedon Dec 7, 2015
@anpete should this go to backlog for now?
anpete commentedon Dec 7, 2015
@rowanmiller Sounds good.
YehudahA commentedon Dec 9, 2015
Why it's go to backlog?!
It's critical for for information and reports systems.
For example, I have 2 million records and I need to show sales by customer. Grouping in client side, is impossible!
ErikEJ commentedon Dec 9, 2015
View/ Indexed view?
103 remaining items
Ben-Pattinson commentedon Feb 27, 2018
@anpete (sorry for the rambling reply)
I probably should have been more specific, I was referring to full framework's EF sql. I have spent literally days trying to get full EF to output sql that did what I meant. Trying to decipher the generated sql was often a nightmare. Getting the same operation was minutes in dapper. This is why I settled on a hybrid approach. Use EF for CRUD and simple selects, dapper for anything complex. When I started porting to core, I was pleased to see the SQL is indeed much more readable, which is a great improvement.... however imho the lack of group-by support makes it a bit of a joke.
The silent nature in which the group-by executes client-side is particularly nasty for the unwary. It reinforces my position of allways checking the SQL EF outputs - which the new generation does really help with.
I can work round this new limitation by simply extending my dapper use, but I'm sure you can see the problems anyone not on a hybrid approach will have.
I appreciate the problems you have when you need to support the same linq syntax for many different types of query, but when personal projects are running rings around your official data layer implementation, something isn't right.
Personally, all I ever wanted was to write sql in my data layer and have it compile time validated against my data layer. It's so much easier and flexible than translating between unrelated syntaxes. I've got that now with dapper, nameof, string interpolation and t4 templates. It would have been nice to get slicker intellisense support, but it's pretty usable.
jzabroski commentedon Feb 27, 2018
jzabroski commentedon Feb 27, 2018
anpete commentedon Feb 28, 2018
@Ben-Pattinson Thanks for the feedback and glad to hear that you have come up with a solution that works for you.
A couple of responses to the points you make: LINQ GroupBy is very different from SQL GROUP BY and so we need client eval here for many cases anyway. It was a shame we weren't able to get to GroupBy with aggregates translation until 2.1, but it is almost here. One reason for this prioritization was that we have the
FromSqlAPI, which gives you a Dapper-like experience for creating queries with raw SQL. Have you tried it? If so, it would be great if you could let us know why it is not working for you - It could be because we didn't have Query Types, which are also landing in 2.1, and make the FromSql experience much better because you no longer need an entity result type.simeyla commentedon Mar 4, 2018
@anpete It's really great to finally see this working :-)
But oddly enough I still receive the error message telling me it cannot translate to GROUP BY, even though the generated SQL right underneath most certainly uses GROUP BY! I assume this must be a known issue?
This is from this source C#
It returns instantly and definitely works as expected so I'm happy for now - just wanted to point this out.
smitpatel commentedon Mar 5, 2018
@simeyla - Thanks for info. I have filed #11157 to track the issue and fix it.
Query: Improvements to Relational GroupBy translation for composition
Query: Improvements to Relational GroupBy translation for composition
Query: Improvements to Relational GroupBy translation for composition
smitpatel commentedon Mar 22, 2018
For preview2 version, there are more patterns now being translated to server (including group by constant). I have updated first post to capture the details.
artemvalmus commentedon Aug 14, 2018
Please let me know if I can solve the following in 2.1.1:
I need to take the latest item from each group, but I receive warnings saying the query cannot be translated. Is there a workaround and is it going to be possible in the foreseeable future?
Example: