LINQ to Entities group-by failure使用.date

我想在日期时间字段的日期部分做一个Linq组。

这个linq语句有效但按日期和时间分组。

var myQuery = from p in dbContext.Trends group p by p.UpdateDateTime into g select new { k = g.Key, ud = g.Max(p => p.Amount) }; 

当我运行此语句仅按日期分组时,我得到以下错误

 var myQuery = from p in dbContext.Trends group p by p.UpdateDateTime.Date into g //Added .Date on this line select new { k = g.Key, ud = g.Max(p => p.Amount) }; 

LINQ to Entities不支持指定的类型成员“Date”。 仅支持初始化程序,实体成员和实体导航属性。

我如何按日期而不是日期和时间进行分组?

使用EntityFunctions.TruncateTime方法:

 var myQuery = from p in dbContext.Trends group p by EntityFunctions.TruncateTime(p.UpdateDateTime) into g select new { k = g.Key, ud = g.Max(p => p.Amount) }; 

这里可能的解决方案遵循以下模式:

 var q = from i in ABD.Listitem let dt = p.EffectiveDate group i by new { y = dt.Year, m = dt.Month, d = dt.Day} into g select g; 

因此,对于您的查询[未经测试]:

 var myQuery = from p in dbContext.Trends let updateDate = p.UpdateDateTime group p by new { y = updateDate.Year, m = updateDate.Month, d = updateDate.Day} into g select new { k = g.Key, ud = g.Max(p => p.Amount) }; 

您不能在Linq-to-Entities查询中使用DateTime.Date 。 您可以显式拥有字段组,也可以在数据库中创建Date字段。 (我有同样的问题 – 我在数据库中使用了一个Date字段,从未回头看过)。