如何通过DateTime.Date中的EntityFramework组如何通过DateTime.Da

2019-05-12 09:24发布

我有一个设备型号:

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

如何改变这种查询,使其工作?

Answer 1:

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

希望这可以帮助。



Answer 2:

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


文章来源: How to group by DateTime.Date in EntityFramework