Fastest Way of Inserting in Entity Framework

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Fastest Way of Inserting in Entity Framework

Message par ForumBot »

Fastest Way of Inserting in Entity Framework
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Fastest Way of Inserting in Entity Framework

Message par ForumBot »

To your remark in the comments to your question:


"...SavingChanges (for each
record)..."

That's the worst thing you can do! Calling `SaveChanges()` for each record slows bulk inserts extremely down. I would do a few simple tests which will very likely improve the performance:

- Call `SaveChanges()` once after ALL records.

- Call `SaveChanges()` after for example 100 records.

- Call `SaveChanges()` after for example 100 records and dispose the context and create a new one.

- Disable change detection

For bulk inserts I am working and experimenting with a pattern like this:

```
using (TransactionScope scope = new TransactionScope())
{
MyDbContext context = null;
try
{
context = new MyDbContext();
context.Configuration.AutoDetectChangesEnabled = false;

int count = 0;
foreach (var entityToInsert in someCollectionOfEntitiesToInsert)
{
++count;
context = AddToContext(context, entityToInsert, count, 100, true);
}

context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}

scope.Complete();
}

private MyDbContext AddToContext(MyDbContext context,
Entity entity, int count, int commitCount, bool recreateContext)
{
context.Set().Add(entity);

if (count % commitCount == 0)
{
context.SaveChanges();
if (recreateContext)
{
context.Dispose();
context = new MyDbContext();
context.Configuration.AutoDetectChangesEnabled = false;
}
}

return context;
}

```

I have a test program which inserts 560.000 entities (9 scalar properties, no navigation properties) into the DB. With this code it works in less than 3 minutes.

For the performance it is important to call `SaveChanges()` after "many" records ("many" around 100 or 1000). It also improves the performance to dispose the context after SaveChanges and create a new

*(Réponse tronquée)*
Répondre

Revenir à « .NET & C# »