How to get a certain number of rows when using the Include method in an entity infrastructure?

I have tables of posts and comments. I can get posts and comments about this:

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

The code above returns all the comments of each post. I want two things:

  • Get 5 comments for each post.
  • Get the total number of comments for each post, receiving only 5 comments of each post.
+4
source share
3 answers

Assuming you have a Post DTO / View model / POCO like this

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();

db.

+2

Include , . :

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

5 :

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

Take(5) 5 , Count() .

+2
source

Source: https://habr.com/ru/post/1617995/


All Articles