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?
4 Answers
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.
-
3Newbie question - let's say I create 10 entities in the loop - 9 of them is 'valid' and one is not (eg. Id = null) - Calling SaveChanges() after loop won't save any entity into the db - is that correct? thx anyone for the clarification– fxdxMay 17, 2018 at 8:05
-
3@fxdx: yes, you're right - since there's at least one error (validation or otherwise), the whole operation of
.SaveChanges()
will fail and nothing will be stored to the database– marc_sMay 17, 2018 at 15:36 -
1@marc_s so what is best way to handle in case of error because of 1 entity out of 1000 lets say ? Dec 5, 2018 at 20:13
-
2@marc_s - What if I have email sending for each item in loop so if I put savechanges outside of loop then even if something might break in savechanges, email will be sent everytime. How to handle this?– NeelApr 29, 2019 at 18:00
-
@Neel I have the same question/case right now. How did you solve it? I'm thinking to create a separate function for this case, meaning to not reuse one that was intended for single entity (i'm building bulk insert of users). Sep 12 at 16:34
One other remark to make is that suppose your foreach loops over an EntitySet that is active in your DbContext you'll get a System.Data.SqlClient.SqlException: another thread is running in the session.
This is because the foreach actually runs in another thread and this is not allowed for the transaction to complete.
This besides the remarks made above that fewer transactions are better.
Suppose you have a context db and do the following:
var groups = from i in db.items select i.GroupNumber;
foreach( var grp in groups)
{
//... do something
db.SaveChanges();
}
This will throw the exception
A solution to avoid this (if appropriate!!) is to 'materialize' the groups entityset by bringing them into Object space by changing the first line into:
var groups = (from i in db.items select i.GroupNumber).ToList();
This will allow you to save in the foreach (if needed)
Out side the loop will create only one transaction to update the database while the other one create one transaction for each iteration. Because EF uses the Unit Of Work Pattern which keeps the all changes in memory and in the SaveChanges method it saves all the changes you made to the DB.
-
Thanks for quick response! So is outside the loop actually faster or is the performance benefit quite minimal?– jaffaJun 21, 2012 at 8:28
-
1yeah it will be more performance in most of the time. Except you have very long running work for one iteration (may be some heavy IO processing). Jun 21, 2012 at 8:32
The performance will be different, inside the loop, you will call the database on each iteration. Outside the loop, you will call the database once. This can make a massive difference in performance depending on how many iterations you have.