LINQ to Entities无法识别方法'Int32 WeeksInYear(System.DateTime)'方法 [英] LINQ to Entities does not recognize the method 'Int32 WeeksInYear(System.DateTime)' method
本文介绍了LINQ to Entities无法识别方法'Int32 WeeksInYear(System.DateTime)'方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个静态课程:
I have a static class:
public class WeekInYear
{
//pass date = DateTime.Now
//return num of this week in calendar
public static int WeeksInYear(DateTime date)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}
}
这是我的linq:
In here is my linq:
int thisWeek = WeekInYear.WeeksInYear(DateTime.Now);
model.NumOfUserCreatedOnThisWeek = Context.Accounts.Where(r => WeekInYear.WeeksInYear(r.CreatedDate) == thisWeek).Count();
然后我收到错误消息:
LINQ to Entities无法识别方法'Int32 WeeksInYear(系统。 DateTime)'method
then I get error message:
LINQ to Entities does not recognize the method 'Int32 WeeksInYear(System.DateTime)' method
推荐答案
我通过创建DateTimeExtensions方法更改它:
I change it by create a DateTimeExtensions method:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
}
之后我用它发现:
After that I use it found:
DateTime thisMonday = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime thisSunday = thisMonday.AddDays(6);
DateTime lastSunday = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
DateTime lastMonday = lastSunday.AddDays(-6);
最后我改变了我的linq:
finally I change my linq:
model.NumOfUserCreatedOnLastWeek = Context.Accounts.Where(r => (r.CreatedDate >= thisMonday) && (r.CreatedDate <= thisSunday)).Count();
这篇关于LINQ to Entities无法识别方法'Int32 WeeksInYear(System.DateTime)'方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文