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

c# entity-framework

Question

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?

1
10
4/3/2016 6:35:28 AM

Accepted Answer

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.

28
6/21/2012 8:35:43 AM

Popular Answer

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)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow