我有一個控制檯線應用程序,通過LINQ將大約150,000行保存到數據庫。這工作正常(我通常會期望它停止工作)。這是一個沼澤標準保存從CSV文件中讀取數據後進行更改來電: -LINQ SaveChanges()異常緩慢
List<Invoice> oldInvoices = db.Invoices.Where(x => !x.IsVisible).ToList();
List<int> oldInvoiceIDs = oldInvoices.Select(s => s.InvoiceID).ToList();
List<InvoiceProduct> allInvoiceProducts = db.InvoiceProducts.ToList();
List<InvoiceProduct> oldInvoiceProducts = allInvoiceProducts.Where(x => oldInvoiceIDs.Contains(x.InvoiceID)).ToList();
db.InvoiceProducts.RemoveRange(oldInvoiceProducts);
db.Invoices.RemoveRange(oldInvoices);
UpdateConsole.WriteLine("Switching over invoices completed. Please wait...", ConsoleColor.Black, ConsoleColor.Magenta);
表是用的產品對每張發票子鏈接表的發票清單。每次我們獲取新數據時,我們都會寫入新數據,在數據庫中將其標記爲不可見,然後將當前可見數據切換爲不可見,並將當前不可見數據切換爲可見數據,從而可以立即切換從一個數據集到下一個數據集。剛剛被標記爲不可見的數據集然後通過LINQ被刪除。
這需要時間來刪除,但不是不合理的時間量。由於此數據來自CSV數據文件,因此我們記錄了行數以及文件讀取的開始和結束日期和時間。這是存儲在另一個數據庫表和代碼保存爲: -
importLog.SuccessfullyImportedRows = successfulRows;
importLog.FailedImportedRows = failedRows;
importLog.EndTime = DateTime.Now;
db.SaveChanges();
這保存,超過40分鐘需要和我不知道爲什麼。我能想到的唯一的事情就是它使用了在Visual Studio中生成EDMX時可用的相同的DBEntities類。
有沒有人有這個?它給應用程序掛的外觀,但它確實持續40分鐘打完...
可能重複[如何更快地運行此任務](http://stackoverflow.com/questions/37374480/how-can-i-run-this-task-faster) – Veverke
可能會幫助您http:// stackoverflow.com/questions/37096509/why-getting-data-with-entity-framwork-is-slow – mohsen
感謝您的鏈接。後者是關於循環內部的SaveChanges(),而我並不是。還值得注意的是,當我保存177,000條記錄時,我保存到本地列表中,然後執行AddRange()和SaveChanges()。我只調用SaveChanges()一次保存列表,第二次保存日誌。沒有任何循環的SaveChanges(),相同的問題仍然存在嗎? –