Sobes.tech
Junior — Middle

Explain how related data is loaded in Entity Framework and how it differs from lazy loading.

sobes.tech AI

Answer from AI

In Entity Framework, loading related data can be done in two main ways:

  1. Eager Loading — related data is loaded immediately along with the main data when executing the query. This is done using the Include method.
var orders = context.Orders.Include(o => o.Customer).ToList();

In this example, related customer data is loaded along with the orders.

  1. Lazy Loading — related data is loaded only when first accessed in the code, i.e., deferred. This requires proxy setup and virtual navigation properties.
var order = context.Orders.First();
var customerName = order.Customer.Name; // A separate database query occurs here

Differences:

  • Eager loading executes all necessary queries at once, reducing database calls but potentially loading unnecessary data.
  • Lazy loading conserves resources by loading data as needed but can lead to multiple separate queries (N+1 problem).

The choice of approach depends on the scenario and performance requirements.

Explain how related data is loaded in Entity… - sobes.tech