9

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.

Marius Orha
  • 670
  • 1
  • 9
  • 26
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • 1
    If you do *Go To Definition* in VS for `Include` method, you'll find a whole help topic describing different `Include` scenarios. Basically you need to use `Select`s to navigate down. – Ivan Stoev Apr 14 '17 at 11:10
  • you can use the other Include. the one which takes a string as a parameter. Then you can do something like this: `Include("Items.Specifications")` – Alex Apr 14 '17 at 11:10

3 Answers3

11

You can also use the notation

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

Note it has to be a string

Mark Wagoner
  • 1,729
  • 1
  • 13
  • 20
8
 Category cat = db.Categories
        .Include(c => c.Items.Select(s => s.Specifications))
        .FirstOrDefault(c => c.Id == 1);
Marius Orha
  • 670
  • 1
  • 9
  • 26
1

Now we can also use:

db.Categories.Include(c => c.Items)
             .ThenInclude(i => i.Specifications);
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171