Back to results for “LINQ”
C# › LINQ

Why can LINQ cause the N+1 query problem and how do you fix it?

Advanced

Answer

Accessing a navigation property inside a loop triggers a query per item. Fix it by eager-loading with Include or projecting the needed data in one query.
// N+1: foreach (var o in orders) use(o.Customer.Name);
var data = db.Orders.Include(o => o.Customer).ToList();
Real-world example A report that reads each order's customer separately hammers the DB; Include batches it.