【问题标题】:Extracting Week number from DateTime value in Linq to entity query从 Linq 中的 DateTime 值中提取周数到实体查询
【发布时间】:2015-02-04 21:10:17
【问题描述】:

在下面的查询中,我收到以下异常:

LINQ to Entities 无法识别方法 'Int32 GetWeekOfYear(System.DateTime,System.Globalization.CalendarWeekRule, System.DayOfWeek)' 方法,并且该方法不能翻译成 存储表达式。

查询:

        var query = db.Cases
            .Where(c => c.UserID == userId
                && ( string.IsNullOrEmpty( dateInterval ) || dateInterval.Equals( ControlValues.Today )? 
                    DbFunctions.TruncateTime( c.EffectiveDate ).Value.Day == currentDayNum :
                    dateInterval.Equals(ControlValues.CurrentWeek) ?
                        CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                            DbFunctions.TruncateTime( c.EffectiveDate ).Value, CalendarWeekRule.FirstFourDayWeek,DayOfWeek.Monday)  == currentWeekNum :
                            dateInterval.Equals(ControlValues.NextWeek) ?
                                CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                                    DbFunctions.AddDays( DbFunctions.TruncateTime(c.EffectiveDate), 7 ).Value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday ) == nextWeekNum :
                                        dateInterval.Equals(ControlValues.CurrentMonth) ?
                                            DbFunctions.TruncateTime(c.EffectiveDate).Value.Month == currentMonthNum :
                                            true)

简而言之,有没有办法从 linq 查询中的数据库值中提取一年中的星期数?

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    使用SqlFunctions.DatePart 静态方法。在生成的 SQL 查询中会转化为DATEPART SQL 函数调用:

    SqlFunctions.DatePart Method

    返回一个整数,表示指定日期的指定日期部分。

    这个函数被翻译成对应的函数 数据库。有关相应 SQL Server 函数的信息, 请参阅 DATEPART (Transact-SQL)。

    要获取周数,请使用"week" 作为参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多