Skip to content
Advertisement

Bulk insert using EntityFramework Extended

According to this, bulk insert in Entity can be made using the following code:

 var customers = GetCustomers();   
 db.Customers.AddRange(customers);   
 db.SaveChanges();  

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

enter image description here

Why?

Advertisement

Answer

AddRange

Add range doesn’t perform a BulkInsert, it simply DetectChanges once after all entities are added to the set.

The DetectChange method can be VERY slow.

See: Entity Framework – DetectChanges Performance

As you noticed, it saves entities one by one in the database which is INSANELY slow.

EF.Extended

This library is not longer supported, and there is no Bulk Insert feature.

Bulk Insert Library

There is three major library supporting Bulk Insert:

Be careful, both free libraries don’t support all inheritances and associations.


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

In addition of Bulk Insert, this library allows you to perform all bulk operations:

  • BulkSaveChanges
  • BulkInsert
  • BulkUpdate
  • BulkDelete
  • BulkMerge
  • BulkSynchronize

Example:

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

// Customize Primary Key
context.BulkMerge(customers, operation => {
   operation.ColumnPrimaryKeyExpression = 
        customer => customer.Code;
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement