c# - Property containing subset of related object -


i have entity post, in one-to-many relationship comment. i'd have property returns 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, code throws

argumentnullexception: value cannot null. parameter name: source

this answer seems suggest that's because filter comments while it's still null. however, in action using method, 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 work? correct approach?

first thing, avoid kind of exception need initialize collection properties in empty entity's constructor:

public post() {   comment=new list<comment>(); } 

second thing use of theninclude suggest me using ef core. if case must use eager loading because version of ef doesn't support lazy loading.

and third thing toplevelcomments property should not mapped part of model:

 modelbuilder.entity<post>()                 .ignore(b => b.toplevelcomments); 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -