属性 包含相关对象的子集

Property containing subset of related object

我有实体 Post,它与 Comment 是一对多关系。我想要 属性 其中只有 returns 个子集:

public class Post
{

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<Comment> TopLevelComments
    {
        get
        {
            return Comments.Where(c => c.ParentID == null).ToList();
        }
    }
}

但是,此代码抛出

ArgumentNullException: Value cannot be null. Parameter name: source

This answer 似乎暗示那是因为我过滤了 Comments,而它仍然是 null。然而,在使用这种方法的行动中,我确实急切地加载它:

var post = await _context.Post.Include(m => m.Author).Include(m => m.Comments).ThenInclude(m => m.Author).SingleOrDefaultAsync(m => m.PostID == id);

我怎样才能让它工作?这是正确的方法吗?

首先,要避免这种异常,您需要在空实体的构造函数中初始化您的集合属性:

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

第二件事是使用 ThenInclude 建议我您正在使用 EF Core。如果是这种情况,您必须使用预加载,因为此版本的 EF 不支持延迟加载。

第三件事是 TopLevelComments 属性 不应映射为模型的一部分:

 modelBuilder.Entity<Post>()
                .Ignore(b => b.TopLevelComments);