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.

Why?

11

2 Answers

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

That's how EF6 does "bulk" insert, it doesn't do in bulk, rather row by row. As a result performance sucks.

Use EF.BulkInsert or EFUtilities instead.

Update:

DbSet<T>.AddRange() is a part of the built-in API, this way you don't use EF.Extended or any other 3rd party library.

6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest