J
J
Jasulan982018-08-06 15:14:15
C++ / C#
Jasulan98, 2018-08-06 15:14:15

Entity Framwork: Get latest message from every conversation?

There is a table Chats
Id Id_1 Id_2 Message DataTime
-------------------------
1 | 95 | 45 | Hello 2018.01.21
2 | 12 | 95 | Hi ....
3 | 32 | 45 | How
4 | 32 | 12 | Hi
5 | 45 | 32 | Hello
6 | 12 | 45 | Hi
My controller

...
[HttpPost]
public async Task<JsonResult> ChatList(int person_id)
{
  IEnumerable<Chat> chats = db.Chats.Where(p=>(p.Id_1==person_id||p.Id_2==person_id));
   return Json(chats);
}

I'm getting the user's entire message here. How do I get the latest message of each conversation?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin, 2018-08-06
@nicebmw9

Call the Last() method on the collection.
If you need the last few, then Skip(arr.count - (minus) the number of messages to display)

M
mefutu, 2018-08-07
@mefutu

You have asynchronous operations, as I understand it, it may happen that the message was the last one, but as a result of multithreading it was written to the penultimate one. Then Last() will give incorrect information.
Here, you first need to sort by DateTime with the choice of the latest through Last ().

C
chibitko, 2018-08-14
@chibitko

you need to group by conversations, then make a projection for each group, selecting only the latest messages

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question