Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在EntityFramework中按DateTime.Date分组_C#_Linq_Entity Framework_Entity Framework 6 - Fatal编程技术网

C# 如何在EntityFramework中按DateTime.Date分组

C# 如何在EntityFramework中按DateTime.Date分组,c#,linq,entity-framework,entity-framework-6,C#,Linq,Entity Framework,Entity Framework 6,我有一个设备型号: 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

我有一个设备型号:

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

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

使用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);
根据MSDN文档,
Date
属性由LINQ to SQL支持,我假设实体框架也支持它

无论如何,请尝试此查询(注意,我使用的方法是为了避免重复解析日期):


希望这有帮助

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