我有实体Post
,它与Comment
是一对多关系。我想要拥有只返回其中某些子集的属性:
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);
关于c# - 包含相关对象子集的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39457105/