According tothis , 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?
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.
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:
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.