使用实体框架在 .Net 6 中获取最后一条消息(发送/接收)

问题描述 投票:0回答:1

要求:使用实体框架在 .Net 6 中获取最后一条消息(发送/接收)。

问题:

.DistinctBy()
无法使用多个参数。

IQueryable<Chat> query = _context.chats
.Include (x => x.Sender)
.Include (x => x.Receiver)
.DistinctBy(x =>(x.senderId),(x.receiverId))
.OrderByDescending(x => x.id);
c# entity-framework linq .net-6.0
1个回答
0
投票

在实体框架中,当使用

DistinctBy
基于多个属性获取不同记录时,您应该为要包含在不同比较中的属性创建一个匿名类型。以下是您可以修改查询以实现此目的的方法:

IQueryable<Chat> query = _context.Chats
    .Include(x => x.Sender)
    .Include(x => x.Receiver)
    .OrderByDescending(x => x.Id)
    .GroupBy(x => new { x.SenderId, x.ReceiverId })
    .Select(group => group.First());
© www.soinside.com 2019 - 2024. All rights reserved.