Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

c# - GetWeekOfYear with Entity Framework

I've a column in my table called Date, and I need to compare this date's WeekOfTheYear with DateTime.Now's WeekOfTheYear,

If I give like this,

var cal = CultureInfo.CurrentCulture.Calendar;

int week = cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);

I am getting 26 here. The same way, in my Entity Framework, I need to compare this week's data, for this I tried like,

entities.WorkingDays.Where(a => 
             cal.GetWeekOfYear(a.DATE,CalendarWeekRule.FirstDay,DayOfWeek.Sunday)
             == cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay,
                                                 DayOfWeek.Sunday)

when I run the query like this, am getting error like,

"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."

How can I fetch the data for weekly basis here, can any one help me out here....thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Call .ToList() first. Like this:

entities.WorkingDays.ToList().Where(a => 
             cal.GetWeekOfYear(a.DATE,CalendarWeekRule.FirstDay,DayOfWeek.Sunday)
             == cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay,
                                                 DayOfWeek.Sunday)

See this post for duplicate issue. Basically, the data needs to be in memory before using your GetWeekOfYear functions.

As noted in the comments, this does bring the whole "WorkingDays" table into memory and therefore fetching more data than needed from the DB. Sometimes this is more preferable to using Stored Procedures and sometimes not, depending on the amount of data and other factors based on your application/database architecture.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...