Nested comments ef core table model returns all comments?

591 Views Asked by At

I have blog post model which save comments and replies in same table.

public class Comment : Entity, IAggregateRoot
{
    private readonly List<Comment> _replies;

    public Comment()
    {
        _replies = new List<Comment>();
    }

    public string CommentText { get; set; }

    public User User { get; set; }

    public Post Post { get; set; }

    public IReadOnlyList<Comment> Replies => _replies;
}

I'm using the following LINQ query to retrieve comments for a specific post.

public async Task<IEnumerable<Comment>> GetCommentsByPostId(Guid postId)
{
    return await Context.Comments
            .AsNoTracking()
            .Include(c => c.Post)
            .Include(c => c.User)
            .Include(c => c.Replies)
            .Where(c => c.Post.Id == postId)
            .ToListAsync();
} 

The thing is this query returns all the comments, I have tried by adding condition as

.Where(c => c.Post.Id == postId && c.Replies.count() == 0)

but this returns replies which haven't replies ,

I need to get nested comments hierarchy from the DB.

can anyone help on this

thanks

0

There are 0 best solutions below