Entity framework Linq to Entities查询以选择最新的、不同的记录

Entity framework Linq to Entities查询以选择最新的、不同的记录,entity-framework,linq-to-entities,umbraco,Entity Framework,Linq To Entities,Umbraco,我试图用Linq to实体检索按DateTime排序的记录,但我也需要它们作为不同的记录 我的桌子设计如下: var distinctComments = (from c in ctx.BlogComments orderby c.date group c by c.blogItemNodeId into uniqueRecords

我试图用Linq to实体检索按
DateTime
排序的记录,但我也需要它们作为不同的记录

我的桌子设计如下:

var distinctComments = (from c in ctx.BlogComments
                        orderby c.date
                        group c by c.blogItemNodeId
                        into uniqueRecords
                        select uniqueRecords.FirstOrDefault());
var distinctComments = ctx.BlogComments.OrderBy(c => c.date)
                        .GroupBy(x => x.blogItemNodeId)
                        .Select(y => y.FirstOrDefault());

其中
blogItemNodeId
是一个Umbraco CMS节点(可以为其创建评论的博客项目节点)

要求是一个博客项目列表可以按评论的数量排序。因此,我需要通过
blogItemNodeId
获取最新的注释,以显示这些博客条目

我当前的linq查询如下所示:

var distinctComments = (from c in ctx.BlogComments
                        orderby c.date
                        group c by c.blogItemNodeId
                        into uniqueRecords
                        select uniqueRecords.FirstOrDefault());
var distinctComments = ctx.BlogComments.OrderBy(c => c.date)
                        .GroupBy(x => x.blogItemNodeId)
                        .Select(y => y.FirstOrDefault());
此查询的问题是,它会查找第一条(因此
FirstOrDefault()
)记录,该记录具有不同的
blogItemNodeId
,其中应该查找具有相同
blogItemNodeId
的所有注释中最新的一条

有人知道如何做到这一点吗?:-)

先谢谢你

编辑

通过这样做,我成功地实现了:

var allComments = (from c in ctx.BlogComments
                   orderby c.date descending
                   select c).ToList();

var distinctComments = allComments.GroupBy(x => x.blogItemNodeId).Select(y => y.FirstOrDefault());
但是在做这个既不优雅也不出色的小组之前,我必须得到所有的评论


非常感谢您的帮助

您可以将orderBy语句和GroupBy语句组合成一个语句,如下所示:

var distinctComments = (from c in ctx.BlogComments
                        orderby c.date
                        group c by c.blogItemNodeId
                        into uniqueRecords
                        select uniqueRecords.FirstOrDefault());
var distinctComments = ctx.BlogComments.OrderBy(c => c.date)
                        .GroupBy(x => x.blogItemNodeId)
                        .Select(y => y.FirstOrDefault());
如果性能不好,可以通过单例将DataContext缓存在HttpCache中。有关示例,请参见。这是基于Umbraco数据上下文的,但是可以很容易地修改以用于其他类型的上下文。

刚刚发现了这个“问题”。你应该在“用编辑回答你自己的问题”部分澄清你找到了答案。这有助于其他人(并增加你的代表积分!)。