Brent Arias
Brent Arias

Reputation: 30165

Eager-loading a tree of entities

I see how to eager load multiple levels of entities with an include statement. But what if I'm loading a tree? Consider this hierarchy of entities:

Now suppose I want to load Alpha entities that have all Bravo, Charlie, and Delta entities added. Can this be done with a single Include statement? I suspect the answer is no, but I'd like to be sure.

Otherwise, I suspect I would simply use two Include statements. But even that gives me pause, because it means I would have to reference Bravo twice (once per Include) statement and I don't know if that confuses EF.

Upvotes: 2

Views: 359

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

It can be done with two Includes like this:

var entities = context.Alphas.Include("Bravos.Charlies")
                             .Include("Bravos.Deltas");

Or this:

var entities = context.Alphas.Include(a => a.Bravos.Select(b => b.Charlies))
                             .Include(a => a.Bravos.Select(b => b.Deltas));

Obviously First is more elegant.

Upvotes: 2

field_b
field_b

Reputation: 698

No, it can't be done with one Include.

You can chain includes like this:

var entities = context.Alphas.Include("Bravos").Include("Bravos.Charlies").Include("Bravos.Deltas");

Upvotes: 2

Related Questions