Reputation: 150108
I have a fairly deep object graph and would like to eagerly load the entire graph.
I'm aware that I can eagerly load specific navigation properties using .Include().
However, that seems fragile (if I add a navigation property, I must also add an additional .Include) and requires (in my case) quite a few .Include() statements.
Is there a way to instruct EF to eagerly load the entire object graph?
Upvotes: 0
Views: 860
Reputation: 150108
However, that seems fragile (if I add a navigation property, I must also add an additional .Include) and requires (in my case) quite a few .Include() statements.
In order to keep all of the code to load the object graph in one place, I created an extension method that can be used from anywhere in the code
static public IQueryable<My> IncludeAll(this DbSet<My> parent)
{
var include = parent
.Include(p => p.CollA)
.Include(p => p.CollB)
.Include(p => p.CollC)
.Include(p => p.CollD)
.Include(p => p.CollE)
.Include(p => p.CollF)
.Include(p => p.Etc);
return include;
}
Usage
var query = ctx.Mys.IncludeAll().Where(...);
Upvotes: 0
Reputation: 364269
You must manually include every navigation property you want to eager load. EF doesn't provide any built in way to include all.
However, that seems fragile (if I add a navigation property, I must also add an additional .Include) and requires (in my case) quite a few .Include() statements.
It is less fragile than automagic include of everything. Such feature would just cause too many problems because in many cases it would eager load navigation properties unexpectedly.
As a workaround you can create some custom extension method which will explore EF metadata of your entity types and add Include
call for every navigation property in your graph.
There are several proposed features for improving eager loading in EF. You can go through them, upvote features you see valuable or propose a new one.
Upvotes: 1