Junior — Middle
Explain the concept of Eager Loading in Entity Framework and when it is used.
sobes.tech AI
Answer from AI
Eager Loading in Entity Framework is a way to load related data along with the main entity in a single database query. This helps avoid the "N+1 query problem," where a separate query is executed for each related record.
It is used when you need to immediately retrieve related objects to avoid additional queries later. For example, if you have an Order entity and related OrderItems, and you want to get all orders along with their items, you apply Eager Loading.
An example using the Include method:
var orders = context.Orders
.Include(o => o.OrderItems)
.ToList();
This loads the orders and their related items at once, improving performance when accessing related data later.