The best way to order included entities in entity framework?

Viewed 54

What is the best practice to order the comment entity?

 public async Task<IList<Post>> GetPosts() {
             var posts = _context.Posts
            .Include(u => u.User)
            .ThenInclude(p => p.Photos)
            .Include(c => c.Comments)   <---- THIS      
            .OrderByDescending(p => p.Created)
            .ToListAsync();

            return await posts;
        }
1 Answers

Before you return the posts, you can order the Comments attached to each post:

var posts = await _context.Posts
                          .Include(u => u.User)
                          .ThenInclude(p => p.Photos)
                          .Include(c => c.Comments)         
                          .OrderByDescending(p => p.Created)
                          .ToListAsync();

foreach(var post in posts)
{
    post.Comments = post.Comments
                        .OrderBy(comment => comment.DateCreated)
                        .ToList();
} 

return posts;

I did the ordering above based on a property called DateCreated. You have to change this to the comment object property, on which you want to base the ordering.

Related