FBryant87
FBryant87

Reputation: 4595

EF Explicitly loading collection within collection

Simple question but from the Entity Framework MSDN examples and other searches I can't see the correct way to do this.

I can explicitly load an EF collection like so:

db.Entry(project).Collection(p => p.Reports).Load();

But if each report has a list of pages within them that need to load, how do I do it? I figured it was something like:

db.Entry(project.Reports).Collection(r => r.Pages).Load();

But this won't work, because 'r' is an ICollection of Reports. What is the correct way to load collections within collections?

Upvotes: 5

Views: 1336

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109079

You can use this syntax:

db.Entry(project).Collection(p => p.Reports)
  .Query()
  .Include(r => r.Pages).Load();

As per MSDN, Query ...

Returns the query that would be used to load this collection from the database. The returned query can be modified

... which means that also Include can be applied to it.

Upvotes: 7

Related Questions