如何使用LINQ在用户之间获取最新消息?

编程入门 行业动态 更新时间:2024-10-21 09:13:08
本文介绍了如何使用LINQ在用户之间获取最新消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个表,显示消息之间的关系.像这样:

I have a table that shows the relationship between messages. Like this:

我想从每个用户那里获得最后一条消息.因此,例如,结果将是表中的ID 91和ID 92

I want to get the last one message from each user. So, for example, result will be id 91 and id 92 from the table

var messages = await _dbContext.Messages.Include(x =>x.User).Where(x =>x.SenderId == userId | x.ReceiveId == userId).OrderByDescending(x =>x.CreatedAt).Select(x =>new Message { Id = x.Id, Content = x.Content, CreatedAt = x.CreatedAt, User = new User { Id = x.User.Id, UserName = x.User.UserName, Name = x.User.Name, LastName = x.User.LastName, Profil = x.User.Profil }, }).Distinct().ToListAsync();

我该怎么办?

推荐答案

答案是:窗口函数,EF不支持.因此,只需编写SQL并通过Dapper运行它

Answer is: Window Functions, which are not supported by EF. So just write SQL and run it via Dapper

SELECT s.Id, s.SenderId, s.ReceiveId, s.Content, s.CreatedAt FROM ( SELECT m.Id, m.SenderId, m.ReceiveId, m.Content, m.CreatedAt, ROW_NUMBER() OVER (PARTITION BY m.ReceiveId ORDER BY m.CreatedAt DESC) AS RN FROM Messages m ) s WHERE s.RN = 1

其他解决方案只是解决方法.如果您需要LINQ来执行此任务,这是我第三次提议 linq2db.EntityFrameworkCore .>

Other solutions are just workaround. It is third time I've proposing linq2db.EntityFrameworkCore if you need LINQ for such task

var query = from m in Messages select new { m.Id, m.SenderId, m.ReceiveId, m.Content, m.CreatedAt, RN = Sql.Ext.RowNumber().Over().PartitionBy(m.ReceiveId).OrderByDesc(m.CreatedAt).ToValue() } var messageQuery = from m in query where m.RN == 1 select new { m.Id, m.SenderId, m.ReceiverId, m.Content, m.CreatedAt, } // switch to alternative LINQ Translator messageQuery = messageQuery.ToLinqToDB();

更多推荐

如何使用LINQ在用户之间获取最新消息?

本文发布于:2023-10-24 14:32:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最新消息   如何使用   用户   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!