如何首先根据 ASP.NET 核心代码中的嵌套 table 对所选数据进行排序

How to order selected data based on nested table in ASP.NET CORE Code first

我有三个表CategoryArticleComment,每个类别有很多文章,每篇文章都有很多评论。 我想 select 所有类别的所有文章按 评论数 排序。 我只能 select 所有按文章排序的类别都这样算:

var query = context.Categories.AsQueryable();

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

但我不能select所有类别都按每个类别中所有文章的评论数排序。

类别class:

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

    public String CategoryName { get; set; }

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

文章class:

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; }
}

评论class:

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

    public String CommentContent { get; set; }

    public int ArticleID { get; set; }

    public Article Article { get; set; }
}

SelectMany 对于这样的事情很方便:

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