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?
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:
- Entity Framework Extensions (Paid but supported)
- EntityFramework.BulkInsert (No longer supported)
- EFUtilities (No longer supported)
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; });