2014-01-17 20 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);