如何首先在ASP.NET CORE代码中基于嵌套表来排序所选数据

时间:2018-01-09 20:24:40

标签: c# entity-framework asp.net-core ef-code-first asp.net-core-mvc

我有三个表类别文章评论,每个类别都有很多文章,每篇文章都有很多评论。 我想在每个类别的所有文章中选择按评论次数排序的所有类别。 我只能选择按文章排序的所有类别:

var query = context.Categories.AsQueryable();

query = query.OrderByDescending(a => a.Articles.Count).Select(a => a);

但我不能在每个类别的所有文章中选择按评论计数排序的所有类别。

分类:

public class Category
{
    public int CategoryID { get; set; }

    public String CategoryName { get; set; }

    public ICollection<Article> Articles { get; set; }
}

文章类:

public class Article
{
    public int ArticleID { get; set; }

    public String ArticleAddress { get; set; } 

    public int CategoryID { get; set; }

    public Category category { get; set; }

    public ICollection<Comment> Comments { get; set; }
}

评论类:

public class Comment
{
    public int CommentID { get; set; }

    public String CommentContent { get; set; }

    public int ArticleID { get; set; }

    public Article Article { get; set; }
}

1 个答案:

答案 0 :(得分:0)

SelectMany对于这样的事情非常方便:

var categoriesByCommentCount = query
    .Select(c => new
    {
        c.CategoryId,
        c.CategoryName, 
        CommentCount = c.Articles.SelectMany(r => r.Comments).Count()
    })
    .OrderByDescending(c => c.CommentCount)
    .ToList();