【问题标题】:Linq query to join two tables and return object from first table - PagedList used用于连接两个表并从第一个表返回对象的 Linq 查询 - 使用 PagedList
【发布时间】:2016-05-24 06:56:15
【问题描述】:

我使用实体框架(代码优先模型) 我有表Posts(postID | Title | ...) 和表Comments(commentID | Comment | postID | userID | CommentDate | ...)

我想要一个基于 cmets 中用户 ID 标准的帖子列表。

var listOfPosts = (from p in db.Posts
                    join coment in db.Comments
                    on p.postID equals coment.postID                                
                    where coment.userID == "Some value"
                    orderby coment.CommentDate descending
                    select p).ToList();


return View("ReportList", listOfReports.ToPagedList(pageNumber, pageSize));

我还使用 PagedList 对帖子进行分页。

但我希望结果按 PostID 分组,所以我修改代码如下

var listOfPosts = (from p in db.Posts
                    join coment in db.Comments
                    on p.postID equals coment.postID
                    where coment.userID == "Some value"
                    orderby coment.CommentDate descending
                    group p by p.postID into newP
                    select newP).ToList();

这里的问题是第二次查询的结果返回List<IGrouping<int, Posts>>和PagedList的ToPagedList方法只适用于List<Posts>

如何更改查询以根据条件和 cmets 顺序返回不同的帖子列表? 您可以使用 lambda 表达式或查询语法。

【问题讨论】:

    标签: entity-framework linq lambda pagedlist


    【解决方案1】:

    您可以尝试在外部查询上使用子查询和 distinct,如下所示:

    var listOfPosts = (from b in ((from p in db.Posts
                                   join coment in db.Comments on p.postID equals coment.postID
                                   where coment.userID == "Some value"
                                   orderby coment.ComentDate descending
                                   select p).ToList())
                       select b).Distinct().ToList();
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 2015-11-15
      • 1970-01-01
      • 2012-06-05
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多