I am using Entity Framework with a MySQL Database and DbContext. I have an entity \"Message\" that has a related entity \"Sender\". (The \"Message\" also has a related entity \"
You don't need the SqlQuery
construct to do the ordering before the grouping:
var refGroupQuery = from m in dbContext.Messages
group m by m.receiver_id into refGroup
let firstItem = refGroup.OrderByDescending(x => x.created_at)
.FirstOrDefault()
select new MessageDTO {
id = firstItem.id,
content = firstItem.content,
sender_email = firstItem.sender.email
};
This does the same, but it translates the whole statement into SQL, which has two advantages
sender
is not lazy loaded for each messagesender.email
does not crash when sender
is null, because in SQL there is no null object reference. The whole expression (sender.email
) just returns null.