There is a table (column RecordDateTime):
20.2.2021 12:54:34
20.2.2021 13:54:34
20.2.2021 14:54:34
20.2.2021 15:54:34
20.2.2021 16:54:34
21.2.2021 11:50:00
21.2.2021 13:54:34
21.2.2021 14:54:34
22.2.2021 10:00:00
22.2.2021 13:54:34
22.2.2021 14:54:34
I need to pick up
20.2.2021 12:54:34
21.2.2021 11:50:00
22.2.2021 10:00:00
and calculate average time.
Here is my current code:
public TimeSpan BeginTime(DateTime startDate, DateTime endDate)
{
var mainGridInfo = from w in db.LogModel
where w.RecordDateTime.Date >= startDate.Date && w.RecordDateTime.Date <= endDate.Date
group w by w.RecordDateTime.Date into test
select test.OrderByDescending(cs => cs.RecordDateTime.TimeOfDay).FirstOrDefault();
var minDatesList = mainGridInfo.Select(s => s.RecordDateTime.TimeOfDay).ToList();
double doubleAverageTicks = minDatesList.Average(timeSpan => timeSpan.Ticks);
long longAverageTicks = Convert.ToInt64(doubleAverageTicks);
return new TimeSpan(longAverageTicks);
}
So as I understand I am grouping by Date into test, then ordering by time portion of DateTime column, then taking First or default (for getting away of possible exceptions). Then I am selecting all available values into new list and calculating average of those? Why my code is producing exceptions? What is wrong?
System.InvalidOperationException: 'The LINQ expression 'GroupByShaperExpression: KeySelector: rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', a.RecordDateTime, 'start of day'), '0'), '.'), ElementSelector:EntityShaperExpression: EntityType: LogModel ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False
.OrderByDescending(cs => cs.RecordDateTime.TimeOfDay)' could not be translated. Either rewrite the query in a form that can betranslated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'