Entity Framework Classic Bulk Delete

Description

The EF Bulk Delete feature let you delete thousands of entities in your database efficiently.

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

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

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

Try it: NET Core | NET Framework

Performance Comparison

Operations 1,000 Entities 2,000 Entities 5,000 Entities
SaveChanges 1,200 ms 2,400 ms 6,000 ms
BulkDelete 50 ms 55 ms 75 ms

Try it: NET Core | NET Framework

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 BulkDelete is faster than SaveChanges?

Deleting thousands 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 performs one database round-trip for every entity to delete. So, if you need to delete 10,000 entities, 10,000 database round-trips will be performed which is INSANELY slow.

The BulkDelete in counterpart requires the minimum database round-trips possible. For example, under the hood of SQL Server, a SqlBulkCopy is performed first in a temporary table, then a DELETE from the temporary table to the destination table is performed which is the most effective tactic available.

Real Life Scenarios

Bulk Delete with custom key

You need to delete a list of Customer but you dont have the IDs, you only have the unique customer codes. The ColumnPrimaryKeyExpression let you to choose the key to use.

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

Try it: NET Core | NET Framework

Documentation

BulkDelete

Methods
Name Description Example
BulkDelete<T>(items) Bulk delete entities in your database. NET Core / NET Framework
BulkDelete<T>(items, options) Bulk delete entities in your database. NET Core / NET Framework
BulkDeleteAsync<T>(items) Bulk delete entities asynchronously in your database. NET Core / NET Framework
BulkDeleteAsync<T>(items, cancellationToken) Bulk delete entities asynchronously in your database. NET Core / NET Framework
BulkDeleteAsync<T>(items, options, cancellationToken) Bulk delete entities asynchronously in your database. NET Core / NET Framework

Learn more

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



Contents

Related