簡體   English   中英

在實體框架中使用Include方法時如何獲得特定的行數?

[英]How to get specific number of rows when using Include method in entity framwork?

我有帖子和評論表。 我可以通過這個獲得帖子和評論:

            List<Posts> posts = db.Posts.Include("Comments").ToList();

上面的代碼返回每個帖子的所有評論。 我想要兩件事:

  1. 獲得每篇文章的5條評論。
  2. 獲取每篇帖子的評論總數,同時每篇帖子只收到5條評論。

您不能使用Include方法來獲得您想要實現的目標。 在以下示例中,結果以匿名類型返回:

var postInfo = db.Posts.Select(p => new
{
    Post = p,
    Comments = p.Comments.Take(5),
    TotalNumberOfComments = p.Comments.Count
})

每篇文章獲得5條評論:

var postWithComments = db.Posts.Select(x => new 
  {
    Post = x,
    Comments = x.Comments.Take(5),
    CommentsCount = x.Comments.Count()
  });

方法Take(5)允許您僅使用內部數據加載5條注釋,方法Count()僅獲取行數。

假設您有這樣的Post DTO / View模型/ POCO

public class PostDto
{
    public string Title{ set; get; }
    public int Id { set; get; }  

    public List<PostDto> Comments { set; get; }

    public int TotalCommentCount { set; get; }
}

以下將獲得評論計數的所有帖子和最后5條評論。 如果需要,您可以更新OrderByDescending以傳遞另一個屬性(如插入時間戳等)

 var posts = dbContext.Posts.
        Select(s => new PostDto
        {
            Id = s.PostId,
            Title= s.PostTitle,
            TotalCommentCount = s.Comments.Count(),
            Comments = s.Comments.OrderByDescending(f => f.Id).Take(5)
                .Select(x => new PostDto
                {
                    Id = x.CommentId,
                    Name = x.CommentText
                }).ToList()
        }).ToList();

這將只對數據庫執行一次查詢。 在此處閱讀延遲執行和性能以獲取更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM