Bulk Update

Description

The EF Bulk Update feature let you update thousands of entities in your database efficiently.

This feature is provided by the library EF Extensions (Included with EF Classic). EF Extensions it's used by over 2000 customers all over the world and support all Entity Framework version (EF4, EF5, EF6, EF Core, EF Classic).

// Easy to use
context.BulkUpdate(customers);

// Easy to customize
context.BulkUpdate(customers, options => options.ColumnPrimaryKeyExpression = customer => customer.Code);

Try it

Performance Comparison

Operations 1,000 Entities 2,000 Entities 5,000 Entities
SaveChanges 1,200 ms 2,400 ms 6,000 ms
BulkUpdate 80 ms 110 ms 170 ms

Try it

HINT:

Performance may differ from a database to another. A lot of factors might affect the benchmark time such as index, column type, latency, throttling, etc.

Why BulkUpdate is faster than SaveChanges?

Updating thousand of entities for a file importation is a typical scenario.

The SaveChanges method makes it quite impossible to handle this kind of situation due to the number of database round-trips required. The SaveChanges perform one database round-trip for every entity to update. So if you need to update 10,000 entities, 10,000 database round-trips will be performed which is INSANELY slow.

The BulkUpdate in counterpart requires the minimum database round-trips as possible. By example under the hood for SQL Server, a SqlBulkCopy is performed first in a temporary table, then an UPDATE from the temporary table to the destionation table is performed which is the most effective tactics available.

Real Life Scenarios

Bulk Update with custom key

You need to update a list of Customer but you doesn't have the ID, you only have the unique customer code. The ColumnPrimaryKeyExpression let you to choose the key to use.

context.BulkUpdate(customers, options => options.ColumnPrimaryKeyExpression = customer => customer.Code);

Try it

Bulk Update specific columns

You need to update a list of Customer but only update some specific column such as FirstName and LastName. The ColumnInputExpression option let you to choose column to update.

context.BulkUpdate(customers, options => { 
	options.ColumnInputExpression = customer => new { customer.FirstName, customer.LastName };
	options.ColumnPrimaryKeyExpression = customer => customer.Code;
});

Try it

You need to update a list of Invoice and include related InvoiceItem. By default, the BulkUpdate doesn't include the graph but you can enable it with the IncludeGraph option.

context.BulkUpdate(invoices, options => options.IncludeGraph = true);

Try it

Learn more

More documentation can be found here: EF Extensions - Bulk Update