Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
FBryant87 Avatar asked Nov 16 '17 11:11

FBryant87


People also ask

What is explicit loading in EF?

Explicit Loading is a technique we query and load the related entities with an explicit call. Explicit loading works very similar to Lazy Loading, but the loading of the related entities happens only after an explicit call. The loading only when we invoke the Load method of the related entity's DBEntityEntry object.

What are different types of loading available to load related entities in EF?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

What difference does AsNoTracking () make?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.

Is lazy loading good EF core?

Lazy loading of data is a pattern whereby the retrieval of data from the database is deferred until it is actually needed. This sounds like a good thing, and in some scenarios, this can help to improve the performance of an application.


1 Answers

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.

like image 94
Gert Arnold Avatar answered Oct 05 '22 22:10

Gert Arnold