如何在EntityFramework中按DateTime.Date分组

5

我有一个设备型号:

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

我希望能按添加日期(仅限日期,而不是日期和时间)对设备数量进行分组选择。但我的当前实现无效,因为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个回答

11

根据这个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()
             };

希望这可以帮到你。


3
很遗憾,EF6不支持日期。关于EntityFunctions类,它已经过时了,我使用DbFunctions代替了它。但是,这个解决方案可行。谢谢。 - alexmac
1
对于进一步的读者,新的未弃用方法是:using System.Data.Entity;中的DbFunctions.TruncateTime() - Christian Gollhardt

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接