Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Last active April 24, 2021 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmatech/57e6bf92828e1ce7c9f70226fbc32f61 to your computer and use it in GitHub Desktop.
Save dharmatech/57e6bf92828e1ce7c9f70226fbc32f61 to your computer and use it in GitHub Desktop.

Regarding your comment:

Btw, if you have stored LinkId for child comments - yes, I know it is redundant and comes from the parent, but it would have given you a simple non hierarchical filter criteria for all link comments, thus the technique with simple Include would have worked.

Excerpt of the Comment class for reference:

    public class Comment
    {
        public int? LinkId { get; set; }
     
        public int? ParentCommentId { get; set; }
        
        ...
    }
  • LinkId is only stored if the comment is a top-level comment.
  • ParentCommentId is only stored if the comment is a reply to another comment.

It sounds like your note is recommending that I always populate LinkId. I.e. even if a comment is a reply to another comment, still store the LinkId value.

If so, then I believe the eager loading code would look like this?

            Link = await _context.Link
                .Include(link => link.User)
                .Include(link => link.Votes)
                .Include(link => link.Comments)
                .Include(link => link.Comments).ThenInclude(comment => comment.User)
                .Include(link => link.Comments).ThenInclude(comment => comment.Votes)
                .FirstOrDefaultAsync(m => m.Id == id);

With my current code, the following:

link.Comments

only returns the top-level comments.

If I implement your suggestion above, it seems like link.Comments will now return all the comments in the tree (top-level as well as replies).

I guess I'd need a method on link like:

link.TopLevelComments()

which returns only the top-level comments?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment