I'm trying to query a database using Linq to get only the last message a patient has sent from every patient from the SmsMessages table. I am trying to group the messages by patient Id, sort the groupings by the date, and then return the first record of that group, like follows:
var sms = await _dataContext.SmsMessages
.GroupBy(message => message.PatientId)
.Select(group => group.OrderByDescending(message => message.CreatedOn).FirstOrDefault())
.ToListAsync();
Several answers to similar questions, for example, suggest doing a variation of the above, but I receive the following error when the query executes: The error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware1 An unhandled exception has occurred while executing the request. System.InvalidOperationException: The LINQ expression '(GroupByShaperExpression: KeySelector: (s.PatientId), ElementSelector:(EntityShaperExpression: EntityType: SmsMessage ValueBufferExpression: (ProjectionBindingExpression: EmptyProjectionMember) IsNullable: False ) ) .OrderByDescending(message => message.CreatedOn)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation.