Borsunho Borsunho - 2 months ago 13
C# Question

Property containing subset of related object

I have entity

Post
, which is in one-to-many relationship with
Comment
. I'd like to have property which only returns certain subset of them:

public class Post
{

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


However, this code throws


ArgumentNullException: Value cannot be null. Parameter name: source


This answer seems to suggest that that's because I filter
Comments
while it's still
null
. However, in action using this method, I do eagerly load it:

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


How can I get this to work? Is this even correct approach?

Answer

First thing, to avoid this kind of exception you need to initialize your collection properties in an empty entity's constructor:

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

Second thing is the use of ThenInclude suggest me you are using EF Core. If that is the case you must use eager loading because this version of EF doesn't support lazy loading.

And third thing is TopLevelComments property should be not mapped as part of your model:

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