I can't seem to rewrite this SQL into EF Linq:
SELECT Conversation.Id
FROM Conversation LEFT JOIN Message
ON Conversation.Id = Message.ConversationId
GROUP BY Conversation.Id
ORDER BY MAX(Message.DateCreated) DESC
I would think something like this would work:
_dbContext.Conversation
.OrderByDescending(c => c.Messages.DefaultIfEmpty().Max(m => m.DateCreated))
.Select(cm => cm.Id);
But this gives me the error System.InvalidOperationException : Sequence contains no elements.
Also this:
_dbContext.Conversation
.Select(c => new {c.Id, MaxDate = c.Messages.DefaultIfEmpty().Max(m => m.DateCreated)})
.OrderByDescending(c => c.MaxDate)
.Select(cm => cm.Id);
But that gives me System.ArgumentException : At least one object must implement IComparable.
.
What is the correct way to do this?