LINQ to Entities group-by failure使用.date

twa*_*amn 17 c# linq linq-to-entities group-by entity-framework-4

我想在日期时间字段的日期部分做一个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) };
Run Code Online (Sandbox Code Playgroud)

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

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) };
Run Code Online (Sandbox Code Playgroud)

LINQ to Entities不支持指定的类型成员"Date".仅支持初始值设定项,实体成员和实体导航属性.

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

Jef*_*ata 32

使用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) };
Run Code Online (Sandbox Code Playgroud)


Per*_* P. 5

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

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;
Run Code Online (Sandbox Code Playgroud)

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

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) };
Run Code Online (Sandbox Code Playgroud)