I'm working on a data integration between two bases, and I'm using Entity Framework for this.
I then generated the following code, which iterates each record in the Situations table of base dbExterno
and feeds my base db
:
foreach (var item in dbExterno.Situacoes)
{
StatusRecursos statusNew = new StatusRecursos();
statusNew.Id = item.CodSit;
statusNew.Nome = item.DesSit;
db.tTipStatusRecursos.Add(statusNew); //Isso se mostrou muito lento!
}
db.SaveChanges();
But I noticed that the above code was very slow, taking minutes to complete an interaction in about 3000 records.
I then changed the code to the code below, and the process took seconds.
In this second code I instead of adding each item to context using Add()
, first feed a generic list of StatusResources, and then add it to the context using AddRange()
.
List<StatusRecursos> listStatus = new List<StatusRecursos>();
foreach (var item in dbExterno.Situacoes)
{
StatusRecursos statusNew = new StatusRecursos();
statusNew.Id = item.CodSit;
statusNew.Nome = item.DesSit;
listStatus.Add(statusNew); //Não foi lento como o código anterior.
}
db.tTipStatusRecursos.AddRange(listStatus);
db.SaveChanges();
I know it got faster, but I do not know why adding the items first in a list and adding to context by AddRange()
was so much faster.
What is the explanation for this?