You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6+Entity Framework获取最新消息:DistinctBy多参数失效

在.NET 6中使用Entity Framework获取最新收发消息(解决DistinctBy多参数问题)

问题原因

.NET 6 中的 DistinctBy 方法仅支持传入单个键选择器参数,你直接传递两个独立参数 (x.senderId),(x.receiverId) 属于语法错误,该方法无法识别这种写法。

基础去重修正写法

如果只是需要对 senderId 和 receiverId 的组合进行去重,可以将这两个字段封装成匿名类型作为键传入 DistinctBy,匿名类型会自动根据所有属性值判断是否重复:

IQueryable<Chat> query = _context.chats
    .Include(x => x.Sender)
    .Include(x => x.Receiver)
    .DistinctBy(x => new { x.senderId, x.receiverId })
    .OrderByDescending(x => x.id);

贴合需求的最优写法(获取每组最新消息)

如果你的实际需求是获取每一对收发方之间的最新消息,单纯用 DistinctBy 去重无法保证保留最新数据,更推荐使用分组筛选的方式:

var latestChats = _context.chats
    .Include(x => x.Sender)
    .Include(x => x.Receiver)
    .GroupBy(x => new { x.senderId, x.receiverId })
    .Select(group => group.OrderByDescending(chat => chat.id).FirstOrDefault())
    .OrderByDescending(chat => chat.id);

逻辑说明:

  • 按收发方ID组合分组
  • 每组内按消息ID降序排序,取第一条(即该对话的最新消息)
  • 最后整体按消息ID降序排列

注意事项

.NET 6 的 Entity Framework Core 完全支持匿名类型作为分组或去重键,上述写法会被正确转换为SQL语句执行,不会产生内存中过滤的性能问题。

内容的提问来源于stack exchange,提问作者Muhammad Bilal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:50:06