如何在EntityFramework中按DateTime.Date进行分组

时间:2014-01-17 12:30:27

标签: c# linq entity-framework entity-framework-6

我有一个设备型号:

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);

如何更改此查询以使其正常工作?

2 个答案:

答案 0 :(得分:11)

嗯,根据this MSDN文档,LINQ to SQL支持Date属性,我假设Entity Framework也支持它。

无论如何,请尝试此查询(请注意我正在使用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()
             };

希望这会有所帮助。

答案 1 :(得分: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);