I am trying to query the database using EF Core 3, group DateTime field by Date and Hours and add Hour part to Date on Select. So far all my Linqs fail.
Fail case 1. Add hours to Date using AddHours.
Logs.GroupBy(g => new
{
g.DateStamp.Date,
g.DateStamp.Hour,
g.Result
}).Select(s => new
{
Date = s.Key.Date.AddHours(s.Key.Hour),
s.Key.Result,
Conversions = s.Count(),
Cost = s.Sum(sum => sum.ConversionCost)
}).OrderBy(o => o.Date)
Error:
The datepart hour is not supported by date function dateadd for data type date.
Not sure exactly where is the problem, AddHours is not supported by Linq to Entity provider or s.Key.Date fields can't contain hours anymore because it becomes Date only field.
Fail case 2. Create new DateTime object and pass variables.
Logs.GroupBy(g => new
{
g.DateStamp.Date,
g.DateStamp.Hour,
g.Result
}).Select(s => new
{
Date =new DateTime(s.Key.Date.Year, s.Key.Date.Month, s.Key.Date.Day, s.Key.Hour, 0, 0),
s.Key.Result,
Conversions = s.Count(),
Cost = s.Sum(sum => sum.ConversionCost)
}).OrderBy(o => o.Date)
Error:
InvalidOperationException: The LINQ expression 'OrderBy<<>f__AnonymousType1, DateTime>( source: Selectf__AnonymousType0, Log>, <>f__AnonymousType1>( source: GroupByf__AnonymousType0, Log>( source: DbSet, keySelector: (l) => new { Date = l.DateStamp.Date, Hour = l.DateStamp.Hour, Result = l.Result }, elementSelector: (l) => l), selector: (e) => new { Date = new DateTime( e.Key.Date.Year, e.Key.Date.Month, e.Key.Date.Day, e.Key.Hour, 0, 0 ), Result = e.Key.Result, Conversions = Count(e), Cost = Sum( source: e, selector: (sum) => sum.ConversionCost) }), keySelector: (e0) => e0.Date)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
The OrderBy(o => o.Date)
stops working and gives an exception, why? I have no idea either.
So the final question would be, how to group DateTime field from SQL Database using EF Core by Date+Hour and move it to Select into one field and also perform OrderBy by new Date field at the end.