实体框架:从每个对话中获取最新消息?

时间:2018-08-06 12:33:31

标签: c# entity-framework

我的桌子聊天

id | sender   | receiver     | message      | date
1  |        1 |            2 | Hello        | 2015-12-08 20:00
2  |        2 |            1 | Hey          | 2015-12-08 20:10
3  |        2 |            1 | You there?   | 2015-12-08 21:00
4  |        1 |            3 | Yes          | 2015-12-08 21:15
5  |        4 |            1 | Hey buddy    | 2015-12-08 22:00

我的控制器

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

如何从每次对话中获取最新消息?

1 个答案:

答案 0 :(得分:1)

var result = db.Chats.GroupBy(c => (Math.Min(c.id1, c.id2), Math.Max(c.id1, c.id2)))
    .Where(g => g.Key.Item1 == person_id || g.Key.Item2 == person_id)
    .Select(g => g.OrderBy(c => c.date))
    .Select(g => g.Last().message);

为了提高效率,您可以将OrderBy替换为Aggregate,这将获取O(n)中的最新元素,但这说明了我认为的概念。