jaffa
jaffa

Reputation: 27350

Any difference between calling SaveChanges() inside and outside a foreach loop?

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?

Upvotes: 21

Views: 26415

Answers (4)

Peter
Peter

Reputation: 27944

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.

Upvotes: 3

Tom
Tom

Reputation: 161

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)

Upvotes: 14

marc_s
marc_s

Reputation: 754488

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.

Upvotes: 47

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

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.

Upvotes: 3

Related Questions