问题
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?
回答1:
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;
});
回答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.
来源:https://stackoverflow.com/questions/43164247/bulk-insert-using-entityframework-extended