Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Include (Eager Load) virtual Property of virtual property [duplicate]

Imagine that we have three Dbsets like below:

Category
{
...
   public virtual ICollection<Item> Items {get; set;}
...
}

Item
{
...
   public virtual ICollection<Specification> Specifications{get; set;}
...
}

Specification
{
...
}

For eager loading I use it like this:

Category cat = db.Categories.Include(c=> c.Items).FirstOrDefault(c=> c.Id == 1);

but now the problem is that

cat.Items[0].Specifications is null, How can we make it to eager load sub collections of the collection too?

P.S.: I tried removing the virtual keyword for testing (I'm don't want to remove it) but it didn't work either.

like image 757
Ashkan Mobayen Khiabani Avatar asked Apr 14 '17 10:04

Ashkan Mobayen Khiabani


2 Answers

Now we can also use:

db.Categories.Include(c => c.Items)
             .ThenInclude(i => i.Specifications);
like image 78
Ashkan Mobayen Khiabani Avatar answered Sep 20 '22 11:09

Ashkan Mobayen Khiabani


You can also use the notation

db.Categories.Include("Items.Specifications")

Note it has to be a string

like image 39
Mark Wagoner Avatar answered Sep 21 '22 11:09

Mark Wagoner