DEV Community

Discussion on: ORMs, Lazy Loading and Web Applications

Collapse
 
ruidfigueiredo profile image
Rui Figueiredo • Edited

Hi Daniel,

.AsNoTracking() isn't related to lazy-loading, it's a way of saying to EF that you don't want it to keep track of those entities. This means that if you make changes to them, those changes won't be persisted when you call .SaveChanges().

Also, if you do something like foreach (var order in cust.Orders) you are not going to end up with a fetch per iteration. There's only going to be 1 db call (adding .ToList() makes no difference in this case). The way you end up with N+1 is if Orders is lazy loaded and you do something like this:

   foreach (var cust in customers)
   {
      foreach (var order in cust.Orders) //one db call per customer for the orders
      {
      }
   }
Enter fullscreen mode Exit fullscreen mode

You are absolutely right about having to really dig deep into the ORM that you are using. Lazy loading and N+1 problems are just one of the ways you can shoot yourself in the foot. Another that comes to mind is validation introducing performance issues when doing bulk inserts.