Entity Framework Insert Records Discover How to Improve Performance
How to do a Bulk Insert?
Inserting thousand of entities for an initial load or a file importation is a typical scenario.
SaveChanges method makes it quite impossible to handle this kind of situation directly from Entity Framework due to the number of database round-trips required.
SaveChanges requires one database round-trip for every entity to insert. So if you need to insert 10000 entities, then 10000 database round-trips will be performed which is INSANELY slow.
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(); }
StackOverflow Related Questions
- How to do a Bulk Insert - Linq to Entities
- How to do Bulk Insert using MySQL (like SqlBulkCopy) with Linq to Entities
Answer
Entity Framework Extensions library adds the BulkInsert extension method to the DbContext. BulkInsert requires the minimum database round-trips as compared to SaveChanges.
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.BulkInsert(customers); }
ZZZ Projects