GROUP BY WEEK EF Core 2.1

Viewed 1510

enter image description here

I need to group per week based on the registration date ?

2 Answers

It's not quite clear what CalendarWeekRule do you have in mind, so assuming you want the simplest (FirstDay), i.e. the formula like

Week = 1 + (DateTime.DayOfYear - 1) / 7

EF Core supports translation of the DayOfWeek to SQL, so you could use something like this (not sure if you need Year):

.GroupBy(g => new { g.Trsdt.Year, Week = 1 + (g.Trsdt.DayOfYear - 1) / 7 })

using System.Globalization;

 .GroupBy( 
              g => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( g.Trsdt, 
              CalendarWeekRule.FirstDay,DayOfWeek.Monday )
           )
Related