Entity Framework Extensions Batch SaveChanges

Description

The EF BatchSaveChanges extension method combine SQL generated by the SaveChanges method. Less database round-trip is performed which improve your application performance.

// var affectedRows = context.SaveChanges();
var affectedRows = context.BatchSaveChanges();

Try it

Performance Comparison

Operations 1,000 Entities 2,000 Entities 5,000 Entities
SaveChanges 1,200 ms 2,400 ms 6,000 ms
BatchSaveChanges 75 ms 150 ms 500 ms

FAQ

What is supported?

  • Entity Framework 6
  • SQL Server
  • Everything SaveChanges support

EF Core support is under development

Why BatchSaveChanges is faster than SaveChanges?

The SaveChanges method makes it quite slow/impossible to handle scenario that requires to save a lot of entities due to the number of database round-trips required. The SaveChanges perform one database round-trip for every entity to insert. So if you need to insert 10,000 entities, 10,000 database round-trips will be performed which is INSANELY slow.

The BatchSaveChanges in counterpart requires the minimum database round-trips as possible. By combining query in fewer command, you might end up by having only 100 database round-trip instead of 10,000.

When should I use BatchSaveChanges over SaveChanges?

Always!

Under the hood, BatchSaveChanges use SaveChanges for saving 1 entity but will outperform in all other cases by combining queries to execute.

Always user BatchSaveChanges is the best of both worlds.

When should I use BatchSaveChanges over BulkSaveChanges?

BatchSaveChanges become slower and slower in comparisons to BulkSaveChanges when the number of entities to save growth due to the ChangeTracker.

After a few thousands of Entities, we recommend using BulkSaveChanges which is a more scalable solution. But be aware, the SQL used is no longer the same as SaveChanges.

Advantages

  • Easy to use
  • Increase performance
  • Increase application responsiveness
  • Reduce database load
  • Reduce database round-trips

Documentation

BatchSaveChanges

Methods
Name Description Example
BatchSaveChanges() Saves all changes made in this context to the underlying database by combining SQL generated. Try it
BatchSaveChangesAsync() Saves all changes asynchronously made in this context to the underlying database by combining SQL generated.
BatchSaveChangesAsync(cancellationToken) Saves all changes asynchronously made in this context to the underlying database by combining SQL generated.

Limitations

  • Support EF6 only
  • Support SQL Server only
  • Might be slower on SQL Express

EF Core and more provider are under development

In this Page