EF Core 6:如何选择每组最新的元素并转换为不同的类

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

我有一个具有以下架构的评论表:

public Class Comments
{
  public string CommenterName {get;set;}
  public string PostId {get;set;}
  public int Id {get;set;}
  public string Message {get;set;}
  public long ModificationTime {get;set;}
} 

我希望创建一个查询,从给定帖子的特定评论者中获取最新评论和 ID。 我尝试过以下代码:

Comment.
Where(comment =\> comment.PostId == postId)
.GroupBy(comment =\> new { comment.CommenterName }, comment =\> comment)
.Select(comment =\> comment.OrderByDescending(i =\> i.ModificationTimeUnixTimeInMs).First()).
.Select(comment =\> new
{
Id = comment.Id,
Message = comment.Message
})
.ToList()

我想要执行最后一个选择的原因是因为随后将结果添加到与另一个查询的联合中以满足分页需求。 (另一个查询也返回 Id 和 Message,但来自另一个表)。

我收到以下错误:“无法翻译 LINQ 表达式 'ProjectionBindingExpression: 0'。

你能帮我吗? 我正在使用 .net 6

c# postgresql linq entity-framework-core
1个回答
0
投票

尝试以下

Comment.OrderByDescending(i => i.ModificationTimeUnixTimeInMs)
       .GroupBy(comment => comment.CommenterName)
       .Select(x => x.First())
       .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.