Javier Flores
Javier Flores

Reputation: 615

GROUP BY WEEK EF Core 2.1

enter image description here

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

Upvotes: 5

Views: 2288

Answers (3)

Ana
Ana

Reputation: 1

This worked for me (.net 8.0):

.GroupBy(x => new
{
  WeekNumber = EF.Functions.DateDiffWeek(x.DocDate.AddDays(-x.DocDate.DayOfYear), x.DocDate) + 1, 

Upvotes: -1

Javier Flores
Javier Flores

Reputation: 615

using System.Globalization;

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

Upvotes: 1

Ivan Stoev
Ivan Stoev

Reputation: 205849

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 })

Upvotes: 8

Related Questions