Improve Entity Framework SaveChanges Performance

Introduction

Problem

You save hundreds, thousands, or millions entities, and your application suffers from performances issues.

# Example

using (var ctx = new CustomerContext())
{
List<Customer> customers = new List<Customer>();
foreach(var line in lines)
{
var customer = new Customer();
// …code…
customers.Add(customer);
}
ctx.Customers.AddRange(customers);
ctx.SaveChanges();
}

Stack Overflow – Related Questions

  • Question 1
  • Question 2


Solution

  • Use BulkSaveChanges (Recommanded)

Use BulkSaveChanges (Recommanded)

Entity Framework Extensions add the BulkSaveChanges extension method to the context.

The method is very easy to use, you simply need to replace SaveChanges by BulkSaveChanges and you are done!

It supports everything:

  • All associations
  • All inheritance (TPC, TPH, and TPT)
  • All operations (Insert, Update, and Delete)

# Performance Comparisons

Operations 1,000 Entities 2,000 Entities 5,000 Entities
SaveChanges 1,000 ms 2,000 ms 5,000 ms
BulkInsert 90 ms 150 ms 350 ms

*: Performance highly vary from a person to another. Some people report us performance improved by over 50 times, some only 10 times.


# How?

1. USE BulkSaveChanges over SaveChanges

2. Done!


# Example

using (var ctx = new CustomerContext())
{
List<Customer> customers = new List<Customer>();
foreach(var line in lines)
{
var customer = new Customer();
// …code…
customers.Add(customer);
}
ctx.Customers.AddRange(customers);
1. USE BulkSaveChanges over SaveChanges
ctx.BulkSaveChanges();
2. Done!
}