Fastest way of inserting many parent and child records

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();
}

Disclaimer: I'm the owner of the project Entity Framework Extensions

Here is the fastest way for inserting, updating, deleting, and merging. You can even make it more easy and use BulkSaveChanges over SaveChanges.

// Using BulkSaveChanges
using (var db = new MyDBContext())
{
    db.ScenarioCategory.AddRange(categories);
    db.BulkSaveChanges();
}

// Using BulkInsert on parent then child
using (var db = new MyDBContext())
{
    db.BulkInsert(categories);
    db.BulkInsert(categories.SelectMany(x => x.Items);
}
链接地址: http://www.djcxy.com/p/33560.html

上一篇: 实体框架4保存并取消

下一篇: 插入许多父母和孩子记录的最快方式