【问题标题】:How to group by DateTime.Date in EntityFramework如何在 EntityFramework 中按 DateTime.Date 分组
【发布时间】:2014-01-17 20:56:15
【问题描述】:

我有一个设备型号:

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

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

【问题讨论】:

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


    【解决方案1】:

    嗯,根据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()
                 };
    

    希望这会有所帮助。

    【讨论】:

    • 不幸的是,EF6 不支持日期。关于 EntityFunctions,这个类已经过时了,我改用 DbFunctions。但是,这个解决方案有效。谢谢。
    • 对于更多的读者,新的不贬低的方法是:DbFunctions.TruncateTime() in using System.Data.Entity;
    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 2020-11-11
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      相关资源
      最近更新 更多