I'm inserting an average of 50,000 records into the database via Entity Framework. And I had a question regarding the following code placements: in the first (1) placement, I use foreach
creating objects with their data and adding them ( contexto.addToTabela
), using SaveChanges()
outside foreach
at the end of the whole process, being used only once. The second (2) placement would be using the SaveChanges()
within the foreach, that is, with each added object there is a commit
. What is the difference between the two situations?
Sample code:
Situation 1:
using (entities contexto = new entities())
{
foreach (var item in lista)
{
...
contexto.AddToTabela(item);
}
contexto.SaveChanges();
}
Situation 2:
using (entities contexto = new entities())
{
foreach (var item in lista)
{
...
contexto.AddToTabela(item);
contexto.SaveChanges();
}
}