I've found this article helpful in doing batch inserts Fastest Way of Inserting in Entity Framework, however, I'm wondering if there is a more efficient way of inserting records with child entities as well.
My entities are like this:
I've been experimenting with BulkInsert and it seems to improve performance a bit, however it is still about 60 seconds for about 40 records each having multiple child entities. I have cases where I'll need to insert thousands of records and it can get extremely slow. My code is as follows:
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 15, 0)))
{
using (var db = new MyDBContext())
{
db.Configuration.AutoDetectChangesEnabled = false;
var entities = db.ScenarioCategory.AddRange(categories);
db.BulkInsert(entities);
db.SaveChanges();
}
transactionScope.Complete();
}