Entity Framework Download Layered Associations

I currently have a database consisting of many related objects.

Simplification with fewer objects:

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

Now I understand that I can 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, it will download all the songs and all the links.

Is there an easier way:

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

Or do I really need to use:

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

This is doable if you have several related objects, but I have like 10 objects that also have subjects ...

Please show me the best way.

+4
source share
2 answers

You just write this:

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

If for some reason this does not actually "Include" (it may fail if you do interesting things in your where clause), check this tip for a workaround: Tip 22 - How to enable Enable really Enable

Hope this helps

Alex

+1
source

You can also write it as (in VB)

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

Source: https://habr.com/ru/post/1286079/


All Articles