Entity Framework Core Tutorial 批量插入
介紹
當你想插入數百,數千甚至數百萬的實體使用SaveChanges()
方法,你會發現你的應用程序的性能是出奇的慢。因為SaveChanges()
要求每個實體插入一個數據庫往返。因此,如果您需要插入10000個實體,那麼將執行10000次數據庫往返,並且您的應用程序會遇到性能問題。
實體框架核心已經取得了很大的進步並且比EF6更快,但是您的應用程序性能甚至可以比使用第三方庫實體框架擴展更快。
BulkInsert
Entity Framework Extensions提供了一個擴展方法BulkInsert ,與SaveChanges()
相比,它需要最少的數據庫往返。通過SQL Server的示例,可以執行簡單的SqlBulkCopy
。
績效比較
操作 | 1,000個實體 | 2,000個實體 | 5,000個實體 |
---|---|---|---|
保存更改 | 1,000毫秒 | 2,000毫秒 | 5,000毫秒 |
BulkInsert | 6毫秒 | 10毫秒 | 15毫秒 |
使用BulkInsert的步驟
- 創建一個列表
- 將實體添加到列表中
- 使用BulkInsert
- 完成!
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! }
閱讀更多: BulkInsert