Junior — Middle
How do you perform lazy or eager loading of a large number of related objects in a system?
sobes.tech AI
Answer from AI
The following approaches are commonly used for lazy (lazy) and eager (eager) loading of related objects in C#:
-
Lazy Loading: related objects are loaded only upon first access. In Entity Framework, this is implemented automatically through proxy objects or by using the
virtualkeyword on navigation properties. -
Eager Loading: related objects are loaded immediately along with the main object, usually using the
Includemethod.
Example with Entity Framework Core:
// Eager loading
var orders = context.Orders.Include(o => o.OrderItems).ToList();
// Lazy loading (if enabled and configured)
var order = context.Orders.Find(1);
var items = order.OrderItems; // Loading occurs here upon first access
The choice of approach depends on the scenario: if you need to get all data immediately — eager loading; if data is needed not always — lazy loading.