Save changes in loop (ARCH204)
Ce contenu n’est pas encore disponible dans votre langue.
Key dotnet.ef.save-changes-in-loop · Severity error · Category ef
Calling SaveChanges on each iteration produces a separate database round-trip per row and severely hurts performance.
Incorrect
Section titled “Incorrect”foreach (var item in items){ _db.Products.Add(new Product { Name = item.Name }); await _db.SaveChangesAsync(); // per-row round-trip}Correct
Section titled “Correct”foreach (var item in items){ _db.Products.Add(new Product { Name = item.Name });}await _db.SaveChangesAsync();Accumulate all changes and call SaveChangesAsync once after the loop.