2011-10-07 77 views
3

在LINQ to SQL中,如何僅比較sql datetime列和.net datetime對象的日期部分?在LINQ中比較日期部分

+2

我知道EF不支持這種轉換,但LINQ to SQL的支持可能使用的日期時間的'.Date'屬性進行比較。 - 只是檢查,它確實。鏈接張貼在我的答案。 – tvanfosson

+0

在EF中,您可以使用[EntityFunctions.TruncateTime](http://msdn.microsoft.com/zh-cn/library/dd395596.aspx)。見http://stackoverflow.com/questions/4188066/linq-to-entities-group-by-failure-using-date –

回答

3

嘗試同時使用的Date屬性:

Date today = DateTime.Today; // Effectively DateTime.Now.Date 

var dataFromToday = from record in context.Records 
        where record.TimeStamp.Date == today 
        select record; 

相信這個工程的LINQ to SQL ...爲tvanfosson說,它並不適用於EF。

+0

我知道它沒有。那是我昨天的事。 – tvanfosson

+0

@tvanfosson:正式做出更強調:) –

+1

也是一個真正的痛苦,因爲我通常嘲笑單元測試的數據上下文,它確實與LINQ一起工作(明顯)。我必須記住,在開發單元測試的存儲庫時,可能會說謊。 – tvanfosson

1

Linq to SQL支持將Date屬性轉換爲SQL以進行比較等。有關支持選項的更多信息,請參見MSDN

0

你可以創建一個CLR UDF來做日期比較,然後在你的linq中將它引用到sql linq查詢中。

0
using System.Data.Objects.SqlClient; //Don't forget this!! 

//You can access to SQL DatePart function using something like this: 

YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL 

//You can compare to SQL DatePart function using something like this: 

DateTime dateToCompare = DateTime.Today; 
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL 
0
using System.Data.Entity; 

DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)