entity framework - Query does not return child collections -


i still struggle this, why each of 'category' items returns null 'task' collections. have data in database, missing?

public class applicationuser : identityuser {     public icollection<category> categories { get; set; } }  public class category {     public int categoryid { get; set; }     public string name { get; set; }     public datetime timestamp { get; set; }      public icollection<task> tasks { get; set; } }  public class task {     public int taskid { get; set; }     public string name { get; set; }     public datetime timestamp { get; set; } } 

and here query:

public ienumerable<category> getallforuser(string name) {     return _ctx.users.where(x => x.username == name)                      .selectmany(x => x.categories)                      .include(x => x.tasks).tolist();     } 

your query falling ignored includes case:

if change query no longer returns instances of entity type query began with, include operators ignored.

as explained in link, if add following dbcontext onconfiguring:

optionsbuilder.configurewarnings(warnings => warnings.throw(coreeventid.includeignoredwarning)); 

then instead null collection you'll invalidoperationexception containing inside error message:

the include operation navigation: 'x.tasks' ignored because target navigation not reachable in final query results.

so how fix that? apparently requirement start query entity want add includes. in case, should start _ctx.categories. in order apply same filter, need add reverse navigation property of application.users category class:

public class category {     // ...     public applicationuser applicationuser { get; set; } } 

now following work:

public ienumerable<category> getallforuser(string name) {     return _ctx.categories         .where(c => c.applicationuser.username == name)         .include(c => c.tasks)         .tolist();     } 

Comments