Entity Framework SaveChanges Performance Discover Why it is Slow
How to Improve SaveChanges Performance?
The DbContext.SaveChanges is a poor choice for BULK operations as far as performance is concerned. Once you get beyond a few thousand records, the SaveChanges method really starts to break down.
using (var ctx = new CustomerContext()) { List<Customer> customers = new List<Customer>(); for(int i = 0; i < 1000; i++) { list.Add(new Customer() { Name ="Customer_" + i}); } context.Customers.AddRange(list); context.SaveChanges(); }
StackOverflow Related Questions
- Entity framework performance issue, saveChanges is very slow
- Entity framework performance slow
- When should I call SaveChanges() when creating 1000's of Entity Framework objects?
Answer
Entity Framework Extensions library adds the BulkSaveChanges extension method to the DbContext. It performs save operations 10 to 50 times faster.
All changes made in the context are persisted in the database but way faster by reducing the number of database round-trip required!
BulkSaveChanges supports everything:
- Association (One to One, One to Many, Many to Many, etc.)
- Complex Type
- Enum
- Inheritance (TPC, TPH, TPT)
- Navigation Property
- Self-Hierarchy
- Etc.
using (var ctx = new CustomerContext()) { List<Customer> customers = new List<Customer>(); for(int i = 0; i < 1000; i++) { list.Add(new Customer() { Name ="Customer_" + i}); } context.Customers.AddRange(list); context.BulkSaveChanges(); }
Improve BulkSaveChanges
BulkSaveChanges is already very fast, but you can make it even faster by simply turning off the EntityFrameworkPropagation option.
EntityFrameworkManager.DefaultEntityFrameworkPropagationValue = false;
When turning off this option, the library does no longer use the methods from Entity Framework but internal methods from our Entity Framework Extensions library.
ZZZ Projects