首页 > 解决方案 > 嵌套评论 ef 核心表模型返回所有​​评论?

问题描述

我有将评论和回复保存在同一张表中的博客文章模型。

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;
}

我正在使用以下 LINQ 查询来检索特定帖子的评论。

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

问题是这个查询返回所有评论,我尝试通过添加条件为

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

但这会返回没有回复的回复,

我需要从数据库中获取嵌套的评论层次结构。

有人可以帮忙吗

谢谢

标签: c#entity-framework-coreef-model-first

解决方案


推荐阅读