Borsunho Borsunho - 1 year ago 74
C# Question

Property containing subset of related object

I have entity

, which is in one-to-many relationship with
. 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
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
while it's still
. 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 Source

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:

                .Ignore(b => b.TopLevelComments);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download