在LINQ语句中检查一周的第一天

时间:2014-09-11 19:25:20

标签: c# linq-to-entities

我想检查当前输入日期是否与数据库中的时间戳相同。我通过查看日期的周数来做到这一点。

我正在尝试使用:

Calendar.GetWeekOfYear(DateTime, ...)

方法,通常有效。

但是,当我使用LINQ时,我得

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

Additional information: LINQ to Entities [...]

我的代码:

 var ordersWeek = orders.Where(c => 
                (EntityFunctions.TruncateTime(c.Timestamp).Value.Year == EntityFunctions.TruncateTime(DateTime.Now).Value.Year) &&
                (EntityFunctions.TruncateTime(c.Timestamp).Value.StartOfWeek(DayOfWeek.Monday) == EntityFunctions.TruncateTime(DateTime.Now).Value.StartOfWeek(DayOfWeek.Monday))
                ).ToList();

在此特定代码中,我尝试使用此扩展方法:

  public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1 * diff);
    }

在LINQ中执行此操作的最佳方法是什么?请记住,您无法使用.Date功能。

1 个答案:

答案 0 :(得分:2)

您的扩展方法StartOfWeek只对您的C#代码可见,实体框架无法转换为基础数据源语言(可能是SQL)。同样,如果您尝试使用Calendar.GetWeekOfYear,它将失败的原因与EF无法翻译它的原因相同。

相反,你可以这样做:

  • 计算一周的开始日期和结束日期
  • 使用该范围在您的LINQ查询中查询,例如c.TimeStamp >= StartDate && c.TimeStamp <= EndDate

代码:

DateTime startDate = dt.StartOfWeek(DayOfWeek.Monday);
DateTime endDate = startDate.AddDays(6);

使用您的扩展方法:

public static class MyExtension
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1*diff);
    }
}

然后在你的LINQ查询中:

var ordersWeek = orders.Where(c =>
                (EntityFunctions.TruncateTime(c.Timestamp).Value.Year == EntityFunctions.TruncateTime(DateTime.Now).Value.Year) &&
                (EntityFunctions.TruncateTime(c.Timestamp).Value >= startDate && 
                EntityFunctions.TruncateTime(c.Timestamp).Value <= endDate)
                .ToList();