3

I'm reading the book Programming Entity Framework: DbContext and I just read the chapter on the three data loading types:

  • Lazy loading (default)
  • Eager loading
  • Explicit loading

Now I'm asking myself which data loading is better in which situation. A concrete comparison would be nice! I haven't found any.

For example, I'm using default lazy loading on a module for a client. This module deals with sales reps and imply these related tables:

  • Reps
  • Reps_Zones
  • Reps_Prerequisites
  • Users
  • Reps_Languages
  • etc.

On the module, I use all these tables to dispatch appointments (about 150 appointments to 50 reps at a time), but it's slow. Would using a different loading strategy really improve the performances?

Judo
  • 5,167
  • 3
  • 24
  • 34
Mathieu
  • 4,449
  • 7
  • 41
  • 60
  • Yeah Lazy loading not the best solution here. Basically you have an `N+1` problem here. Means that every time you access an entity it is running a select statement to load just that entity. Imagine looping through a bunch of objects. A lot queries there. Better to eager load or I guess explicit load what you will need using the query builders or linq. – Gohn67 May 19 '12 at 03:26
  • See here about N+1 problem with lazy loading in orm's http://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem – Gohn67 May 19 '12 at 03:27

1 Answers1

2

Lazy-loading seems most suitable for smaller apps without separate data layers. Once the app grows and you start separating it into separate layers, lazy loading becomes less useful. The DBcontext has long since been destroyed by the time the data gets to the UI layer, and while you are within the datalayer it is not a big deal to specify the properites to load.

Lazy loading is turned off for validation, so if a property is marked as required and you have only loaded the parent an error will always be thrown which is very frustrating.

Lazy loading also makes debugging rather tricky as the query isnt executed until it is used so you can't examine the results of the query as easily. I usually add a ToList() or similar to my EF queries so I can easily examine the results.

Judo
  • 5,167
  • 3
  • 24
  • 34