如何在Entity Framework Core中按週分組?

.net-core entity-framework-core group-by linq week-number

在Entity Framework 6中,我可以使用SqlFunctions.DatePart()方法:

var byWeek = data.GroupBy(x => SqlFunctions.DatePart("week", x.Date));

但是這些類( DbFunctionsSqlFunctions在Entity Framework Core中不可用)( 參考 )。

所以我的問題是如何在Entity Framework核心中按週分組?

熱門答案

我目前缺少功能的解決方法是

var firstMondayOfYear = this.GetFirstMondayOfYear(DateTime.Now.Year);
var entries =
    this.entitiesService.FindForLastMonths(this.CurrentUser.Id, 6)
        .GroupBy(x => ((int)(x.Date - firstMondayOfYear).TotalDays / 7))

函數GetFirstMondayOfYear

private DateTime GetFirstMondayOfYear(int year)
{
    var dt = new DateTime(year, 1, 1);
    while (dt.DayOfWeek != DayOfWeek.Monday)
    {
        dt = dt.AddDays(1);
    }

    return dt;
}

此分組給出當前年份的周數和前幾年的負值。

稍後您可以使用此getter獲取周名稱:

public string WeekName
{
    get
    {
        var year = DateTime.Now.AddYears((int)Math.Floor(this.WeekNumber / 52.0)).Year;
        var weekNumber = this.WeekNumber % 52;
        while (weekNumber < 0)
        {
            weekNumber += 52;
        }

        return $"{year}, W{weekNumber}";
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow