views:

198

answers:

2

I currently have a database that consist of many linked objects.

Simplified with less objects:

Song => Versions => Info
          ||
          \/
         Data

Now I understand that I can eager load all these objects when using

db.Song.include("Versions.Data").Include("Versions.Info").ToList();

However, when I just want 1 song with its data this will cause to load all the songs and all the references.

Is there an easier way like :

db.Song.First().include("Versions.Data").Include("Versions.Info")

Or do I really have to use:

Song.Versions.Load();
foreach( Version version in versions)
{ 
    version.DataReference.Load();
    version.InfoReference.Load();
}

It is doable if you have a few related objects, but I am having like 10 objects that have subojects themselves too...

Please show me a better way.

+1  A: 

You just write this:

var song = (from s in db.Song.Include("Versions.Data").Include("Versions.Info")
           where s.ID == 1 // i.e. some filter here
           select s).First();

If for some reason this doesn't actually do the 'Include' (it might fail if you do interesting things in your where clause) check this Tip out for a workaround: Tip 22 - How to make Include really Include

Hope this helps

Alex

Alex James
But does that not load first all the songs and references and then select the first one? IE: Does it really only load the references of song with id=1?
Peterdk
It only loads the references to song 1.
Alex James
A: 

You could also write it like (in VB)

dim song = db.Song.Include("Versions.Data").Include("Versions.Info").Where(Function(s) s.ID = 1).FirstOrDefault()
Detroitpro