Is there any performance benefit/technical differences between calling EF SaveChanges() in a foreach loop or outside a loop, assuming a change is made to an EF entity inside the loop?
Is there any performance benefit/technical differences between calling EF SaveChanges() in a foreach loop
Share
YES!
If you call it inside the loop, EF will write back the changes to the database for every single entity (and every entity will be in its own, separate transaction).
The other way around, you’ll make all your changes and EF will write them back all at once after the loop (in one single transaction for all entities together).
As a general rule of thumb (without actually seeing your code) try to have as few calls to
.SaveChanges()as possible.One call with 50 changes is typically much better / faster / more efficient than 50 calls for 1 change each.