I'm trying to insert about 2000-5000 records with 60 fields with EF6 MVC.
This is my code :
using (var db = new MyEntities())
{
using (var transaction = db.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
{
try
{
db.Database.CommandTimeout = 180;
// ToInsertStatement is an ExtensionMethod
// which generates a sql INSERT statement from list of entities
// in *N* batch size.
// INSERT INTO tbl values(),()*N*(); INSERT INTO...
db.Database.ExecuteSqlCommand(entitiesList.ToInsertStatement(20));
// Some other changes
db.SaveChanges();
transaction.Commit();
}
catch (Exception exception)
{
transaction.Rollback();
}
}
}
According to Admir's answer, I send every 20 records with one INSERT statement and fortunately ExecuteSqlCommand
takes only 6 seconds. BUT SaveChanges()
takes about 2 minutes!
How can I overcome this problem?