从Linq中的DateTime值提取周号到实体查询 [英] Extracting Week number from DateTime value in Linq to entity query

查看:162
本文介绍了从Linq中的DateTime值提取周号到实体查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the bellow query i'm getting the following exception:


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

LINQ to Entities does not recognize the method 'Int32 GetWeekOfYear(System.DateTime, System.Globalization.CalendarWeekRule, System.DayOfWeek)' method, and this method cannot be translated into a store expression.

查询:



        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查询中的数据库值中提取年份的一周?

Question in short, is there a way to extract the week of the year number from a database value in linq queries?

推荐答案

使用 SqlFunctions.DatePart static方法。它将被转换为 DATEPART 生成的SQL查询中的SQL函数调用:

Use SqlFunctions.DatePart static method. It will be transformed into DATEPART SQL function call in generated SQL query:


< a href =http://msdn.microsoft.com/en-us/library/dd487171%28v=vs.110%29.aspx =nofollow> SqlFunctions.DatePart 方法

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

Returns an integer that represents the specified datepart of the specified date.

此函数转换为
数据库中的相应函数。有关相应的SQL Server功能的信息,
请参阅DATEPART(Transact-SQL)。

This function is translated to a corresponding function in the database. For information about the corresponding SQL Server function, see DATEPART (Transact-SQL).

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

To get week number, use "week" as parameter.

这篇关于从Linq中的DateTime值提取周号到实体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆