Advertisement
ivandrofly

N+1 problem example

Jul 30th, 2023
1,180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.47 KB | None | 0 0
  1. // Example of N+1 problem
  2. var orders = context.Orders.ToList();
  3. foreach(var order in orders)
  4. {
  5.    var customer = context.Customers.Find(order.CustomerId);
  6.    Console.WriteLine($"Order {order.Id} belongs to {customer.Name}");
  7. }
  8.  
  9. // Avoiding N+1 problem by eager loading
  10. var orders = context.Orders.Include(o => o.Customer).ToList();
  11. foreach(var order in orders)
  12. {
  13.    var customer = order.Customer;
  14.    Console.WriteLine($"Order {order.Id} belongs to {customer.Name}");
  15. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement