How to get latest record for each group using Entity Framework and MySQL including related entity

前端 未结 1 567
北海茫月
北海茫月 2021-01-27 22:33

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 \"

相关标签:
1条回答
  • 2021-01-27 23:01

    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 message
    • sender.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.
    0 讨论(0)
提交回复
热议问题