2011-01-24 29 views
1

使用我有以下SQL命令:翻譯SQL語句日期的LINQ到SQL與EF4

SELECT  CONVERT(varchar, Logged, 103) AS Visited, COUNT(ID) AS Totals 
FROM   tblStats 
GROUP BY CONVERT(varchar, Logged, 103) 
ORDER BY Visited DESC 

我要翻譯成可以與實體框架使用的L2S聲明中,但在使用日期時間類型時,根據我如何嘗試攻擊問題,我得到各種錯誤。

方法:

var results = from s in db.Stats 
     group s by (s.Logged.Date.ToString()) into Grp 
     select new { Day = Grp.Key, Total = Grp.Count() }; 

錯誤:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

方法:

var results = from s in db.Stats 
       group s by (s.Logged.Date) into Grp 
       select new { Day = Grp.Key, Total = Grp.Count() }; 

錯誤:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我需要什麼語法才能使查詢工作?

回答

1

嘗試使用EntityFunctions.TruncateTime方法:

var results = from s in db.Stats 
       group s by EntityFunctions.TruncateTime(s.Logged) into Grp 
       select new { Day = Grp.Key, Total = Grp.Count() }; 
+0

這就是問題!謝謝。現在我有一個不同的問題,但我會爲此提出一個新問題。 – 2011-01-24 21:47:02

0

你需要s.Logged.DateDate部分?

你有沒有嘗試過這樣的:

var results = from s in db.Stats 
       group s by (s.Logged) into Grp 
       select new { Day = Grp.Key, Total = Grp.Count() }; 

我假設Logged是屬性(列在表中)。

編輯:你們是快速的方式。

+0

如果您不使用`Date`部分,那麼您將按照完整的日期時間進行分組,包括時間分量。 – 2011-01-24 22:14:53