Entity Framework. SQL Group by EF Group By

I am trying to define a standard way to group by year, month, day, hour, etc.

While reading some SQL documentation, it seems the most efficient way would be to use:

GROUP BY dateadd(month, datediff(month, 0, CreatedDate), 0)

Pay attention to the "month", "year", ...

Then I tried to replicate this using:

.GroupBy(x => SqlFunctions.DateAdd("month", SqlFunctions.DateDiff("month", 0, x.Created), 0))

.GroupBy(x => EntityFunctions.AddMonths(EntityFunctions.DiffMonths(0, x.Created)))

However, both expressions could not be compiled ...

And I'm not sure what is the way to do this?

How to correctly replicate this line of SQL code in EF?

+5
source share
1 answer

I don’t understand. Why do you want to use standard sql to do this in any way, however it can be done easily with LINQ, and this will be a more standard grouping by an anonymous type, for example:

.GroupBy( x => new 
               {
                  month = x.CreatedDate.Month,
                  year = x.CreatedDate.Year,
                  ...
               });
+5
source

All Articles