2014-01-17 32 views
4

組有一個設備型號:我如何通過DateTime.Date中的EntityFramework

public class DeviceModel 
{ 
    public DateTime Added { get;set; } 
} 

,我想選擇的設備計數,通過Added日期分組(沒有日期和時間,但迄今只有)。我目前的實現是無效的,因爲LINQ無法翻譯DateTime.Date到SQL:

var result = (
    from device in DevicesRepository.GetAll() 
    group device by new { Date = device.Added.Date } into g 
    select new 
     { 
      Date = g.Key.Date, 
      Count = g.Count() 
     } 
    ).OrderBy(nda => nda.Date); 

如何改變這種查詢,使其工作?

回答

10

那麼,根據this MSDN文檔,Date屬性由支持LINQ to SQL和我認爲實體框架支持它。

不管怎麼說,嘗試此查詢(請注意,我使用的是爲了TruncateTime方法,以避免重複解決日期):

var result = from device in 
       (
        from d in DevicesRepository.GetAll() 
        select new 
        { 
         Device = d, 
         AddedDate = EntityFunctions.TruncateTime(d.Added) 
        } 
       ) 
      orderby device.AddedDate 
      group device by device.AddedDate into g 
      select new 
      { 
       Date = g.Key, 
       Count = g.Count() 
      }; 

希望這有助於。

+3

不幸,EF6不支持日期。關於EntityFunctions,這個類已經過時了,我改用了DbFunctions。但是,這個解決方案可行。謝謝。 – alexmac

+1

對於更多的讀者,新的未描述的方法是:'使用System.Data.Entity'中的DbFunctions.TruncateTime()'; –

1

使用EntityFunctions.TruncateTime

var result = (
from device in DevicesRepository.GetAll() 
group device by new { Date = EntityFunctions.TruncateTime(device.Added)} into g 
select new 
    { 
     Date = g.Key.Date, 
     Count = g.Count() 
    } 
).OrderBy(nda => nda.Date);