Entity Framework Fastest Way To Insert Improve Save Performance
What's the fastest way to insert?
When you want to insert hundreds, thousands, or millions of entities, and your application suffers from performances issues.
StackOverflow Related Questions
- Fastest Way of Inserting in Entity Framework
- Writing to large number of records take too much time using Entity Framework
Answer
BulkInsert
There are many solutions to insert many records in the fastest way, but the most significant and recommended solution is BulkInsert provided by Entity Framework Extensions library. By default, identity value is populated to make it even easier to use.
Performance Comparisons
Operations | 1,000 Entities | 2,000 Entities | 5,000 Entities |
---|---|---|---|
SaveChange | 1,000 ms | 2,000 ms | 5,000 ms |
BulkInsert | 6 ms | 10 ms | 15 ms |
Steps to use BulkInsert
- CREATE a list
- ADD entity to the list
- USE BulkInsert
- Done!
using (var ctx = new CustomerContext()) { // 1. CREATE a list List<Customer> customers = new List<Customer>(); foreach(var line in lines) { var customer = new Customer(); // ...code... // 2. ADD entity to the list customers.Add(customer); } // 3. USE BulkInsert ctx.BulkInsert(customers); // 4. Done! }
Alternative to BulkInsert
There are some free third-party libraries alternative to Entity Framework Extensions, they are not hard to find, but we don't recommend them since they work with the simple scenario but fail at supporting complex type, inheritance, and association.
SqlBulkCopy
Using SqlBulkCopy (for SQL Server) is without a doubt the fastest solution (very slightly faster than Entity Framework Extensions) but also the longer to implement.
Be careful; this solution adds some code complexity for the maintenance team.
Steps to use SqlBulkCopy
- CREATE a list
- ADD entity to the list
- CONVERT the list to a DataTable
- CREATE a SqlBulkCopy instance
- MAP the SqlBulkCopy to database
- Use WriteToServer
- Done!
ZZZ Projects