Group by hour in IQueryable

后端 未结 1 505
粉色の甜心
粉色の甜心 2021-01-20 11:42

In my project I receive some data from an SPS all x seconds. Every y minutes I archive the current Data in a database so I\'m able to show statistics.

The data I r

1条回答
  •  执笔经年
    2021-01-20 12:21

    The key part of the GroupBy can easily be made translatable by avoiding new DateTime(...) and using either anonymous type

    .GroupBy(d => new { d.ArchiveTime.Date, d.ArchiveTime.Hour })
    

    or Date property + AddHours:

    .GroupBy(d => d.ArchiveTime.Date.AddHours(d.ArchiveTime.Hour))
    

    Unfortunately currently (EF Core 2.2) does not translate nested First / FirstOrDefault / Take(1) to SQL and uses client evaluation. For First() it is forced in order to emulate the LINQ to Objects throwing behavior, but for the other two patterns it's caused by the lack of proper translation.

    The only server side solution I see for your concrete query is to not use GroupBy at all, but correlated self antijoin, something like this:

    var onePerHour = dataLastWeek.Where(d => !dataLastWeek.Any(d2 =>
        d2.ArchiveTime.Date == d.ArchiveTime.Date &&
        d2.ArchiveTime.Hour == d.ArchiveTime.Hour &&
        d2.ArchiveTime < d.ArchiveTime));
    

    0 讨论(0)
提交回复
热议问题