0

Does finding an entity using a key (like follows) eagerly load all related entities implicitly?

var person = context.People.Find(1);

Say the People entities have related Children entities, would they be eagerly loaded in the above lookup or would the following query be more suitable?

var person = context.People.Include("Children").First(p => p.Id == 1);

If the Children entities are not eagerly loaded using Find, and the database has to be hit again in order to fetch them (I assume), which of the methods is likely to be better performing?

Again, if the Find method does not eagerly load the Children entities, what is the correct way to load them?

Finally, is there some configuration that would cause the Children - or even all related - entities to be eagerly loaded when using Find?

Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
psand2286
  • 45
  • 1
  • 5

1 Answers1

0

Here is the answer to your questions about the Find method. Entity Framework Code First Find vs SingleOrDefault (Eager Loading)

If the Children entities are not eagerly loaded using Find, and the database has to be hit again in order to fetch them (I assume), which of the methods is likely to be better performing?

Generally speaking, with SQL, loading data in bulk is faster and if EF has to load your child entities based on IDs, it's going to submit a query to the DB for each entity rather than loading them in bulk or it might use a WHERE ID IN (1,2,3,4,5). Either way, this is slower than if you were to load your entities with a join on the child table so the eager loading should be faster, but this will all depend on exactly what queries EF generates and your database schema.

The best way to approach this is to profile your SQL server in order to see what queries are being generated by EF and then producing a script that replicates them and time the scripts.

Community
  • 1
  • 1
Aaron Hawkins
  • 2,371
  • 17
  • 24
  • Thanks Aaron. How would I use `Join`? – psand2286 Oct 21 '14 at 14:11
  • I'm not exactly sure what you're asking, but does this answer your question? http://stackoverflow.com/questions/315966/how-do-you-construct-a-linq-to-entities-query-to-load-child-objects-directly-in – Aaron Hawkins Oct 21 '14 at 14:19
  • You said 'Either way, this is slower than if you were to load your entities with a join on the child table'. Perhaps I misunderstood that statement; by 'join' are you referring to eager loading like this `var person = context.People.Include("Children").First(p => p.Id == 1);`? – psand2286 Oct 21 '14 at 14:36
  • Yes, although your filter statement pulling only the record wtih Id equal to 1 essentially brings that statement to approximately the same relative speed. You will only see the speed increases using the Include method if you pull a large set of the entities. – Aaron Hawkins Oct 21 '14 at 14:42