tafkab76
tafkab76

Reputation: 475

EF: Loading related objects of related objects

I can´t find a way to load an object from a DB with all its related objects. Concerning this simplified model (ID-Properties not shown):

class MainClass 
{  
    public virtual ICollection<FirstLevelClass> FirstLevelObjects {get; set;}  
}

class FirstLevelClass
{  
    public virtual ICollection<SecondLevelClassA> SecondLevelObjectsA {get; set;}
    public virtual ICollection<SecondLevelClassB> SecondLevelObjectsB {get; set;}
}

class SecondLevelClassA
{
    public virtual int SomeValue {get; set;}

}
class SecondLevelClassB
{
    public virtual int SomeValue {get; set;}

}

The DbContext is on "MainClass"-Objects:

public SampleContext : DbContext
{
    public DbSet<MainClass> MainClassObjects {get; set;}
}

How can I load an MainClass-object from db with all first- and second-level-objects? I can do:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects).ToList();

    // ...move objects from the context to program logic...

}

but how do I get SecondLevelObjects? I´m missing something like:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects.SecondLevelObjects).ToList();

    // ...move objects from the context to program logic...

}

Is this even possible or do I have to adapt the DbSets in the DbContext?

Upvotes: 1

Views: 170

Answers (2)

Loetn
Loetn

Reputation: 4040

Try this:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects.SelectMany(s => s.SecondLevelObjects)).ToList();

// ...move objects from the context to program logic...

}

You should add a .Select() statement to get an object or a list.

Upvotes: 1

VahidNaderi
VahidNaderi

Reputation: 2488

One solution can be to use Include method's other overload which takes a string like this:

var MainClassObjects = context.MainClassObjects
.Include("FirstLevelObjects")
.Include("FirstLevelObjects.SecondLevelObjects")
.ToList();

Update:

When you're using this method you just need to determine the paths you want to fetch so for updated question you can use this:

var MainClassObjects = context.MainClassObjects
.Include("FirstLevelObjects.SecondLevelObjectsA")
.Include("FirstLevelObjects.SecondLevelObjectsB")
.ToList();

Upvotes: 2

Related Questions