16
I’m working on a data integration between two databases, and I’m using Entity Framework for that reason.
I then generated the following code, which iterates each record in the Base Situations table 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();
However I noticed that the code above was very slow, taking minutes to complete an interaction in about 3000 records.
I changed it then to the code below, and the process took seconds.
In this second code I instead of adding each item to the context using Add()
, first feed a generic list of Statusrecursos, and then add 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 don’t know why add the items first in a list and add to context for AddRange()
was so much faster.
What is the explanation for this?
Actually, disabling the check
Add
got as fast as theAddRange
– Guilherme de Jesus Santos