2011-09-21 54 views
3

EF 4 in C#。如何使用EF 4從當前日期獲取最近兩天內的所有記錄?

我有我的查詢,目前我能夠通過當前的日期(只是不考慮TIME的日期)過濾結果。

我需要篩選結果從最後兩天到當前日期(不知道該怎麼做)。

我試過在我的查詢currenteDate - 2但沒有成功。

你能舉個例子嗎?感謝您的時間。

DateTime currenteDate = DateTime.UtcNow.Date; 

       var contents = from cnt in context.CmsContents 
           where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date == currenteDate 
           orderby cnt.ContentId descending 
           select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent }; 

回答

7

要更改當前日期,您需要使用currenteDate.AddDays(-2)。並使用>=代替==前,直到最後一個記錄得到2天的所有記錄

DateTime currenteDate = DateTime.UtcNow.Date.AddDays(-2); 

var contents = from cnt in context.CmsContents 
        where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date >= currenteDate 
        orderby cnt.ContentId descending 
        select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent }; 
+0

抱歉,但我需要的所有記錄從兩個幾天前到目前爲止,你的代碼在第一次看起來似乎提供了兩天前的所有記錄。我對麼? – GibboK

+0

我在答案中添加了評論。檢查最新的代碼示例。我已將'=='更改爲'> ='。 – Samich

+0

我得到這個錯誤:LINQ to Entities不能識別方法'System.DateTime AddDays(Double)'方法,並且這種方法不能被轉換成商店表達式..任何想法? – GibboK

0

使用來自的DateTime對象的比較方法:

cnt.Date.CompareTo(DateTime.Now.AddDays(-2)) >= 0 
+0

錯誤:LINQ to Entities無法識別方法'System.DateTime AddDays(Double)' – GibboK

+0

你使用DateTime.Now.AddDays(-2)(RIGHT!)還是隻是簡單地使用DateTime.AddDays(-2)(錯誤! )? – Viper

+0

也許這有助於:[其他SO帖子](http://stackoverflow.com/questions/4146300/lnq-to-ef-datetime-problem)'EntityFunctions.AddDays(p.StartDate,p.Period)'...似乎EF在這個問題上有一個特殊的功能。 – Viper

相關問題