我有> 67000條記錄從另一個來源進入我的系統。在將業務規則應用於這些記錄之後,我必須將它們存儲到數據庫中。實體框架(EF)OutOfMemoryException
Error in executing code|Exception of type 'System.OutOfMemoryException' was thrown.* at System.Data.Mapping.Update.Internal.KeyManager.<WalkGraph>d__5.MoveNext()
at System.Data.Mapping.Update.Internal.KeyManager.GetPrincipalValue(PropagatorResult result)
at System.Data.Mapping.Update.Internal.UpdateCompiler.GenerateValueExpression(EdmProperty property, PropagatorResult value)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildSetClauses(DbExpressionBinding target, PropagatorResult row, PropagatorResult originalRow, TableChangeProcessor processor, Boolean insertMode, Dictionary`2& outputIdentifiers, DbExpression& returning, Boolean& rowMustBeTouched)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildInsertCommand(PropagatorResult newRow, TableChangeProcessor processor)
at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler)
at System.Data.Mapping.Update.Internal.UpdateTranslator.<ProduceDynamicCommands>d__0.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()
at System.Data.Mapping.Update.Internal.UpdateCommandOrderer..ctor(IEnumerable`1 commands, UpdateTranslator translator)
at System.Data.Mapping.Update.Internal.UpdateTranslator.ProduceCommands()
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
我使用EF 4.0
using (var context = new MyEntities())
{
var importDataInfo = context.ImportDataInfoes.First(x => x.ID == importId);
importedRecords.ForEach(importDataInfo.ValuationEventFulls.Add);
context.SaveChanges();
}
執行代碼我收到以下錯誤(OutOfMemoryException異常)後:我用下面的代碼做這件事。
我的問題是有限制的記錄數量保存?保存大量記錄的最佳做法是什麼(將它們保存在塊中?關於事務呢?)。
謝謝大家。
感謝您的回覆。 - 是的,我更改了我的代碼以測試它是否與大塊記錄一起工作,並且確實有效,但是我的問題是我沒有閱讀任何有關EF中SaveChanges()限制記錄數的任何內容。你有沒有聽說過MS的這個限制? – 2011-05-12 16:26:20
@Vlad Bezden該限制不是專門針對EF,它只是使用.NET技術的一部分。當你ETL 67K記錄時,你可能在內存中有200k +對象。你有67k原始記錄,你有67k EF對象,並且每個對象最有可能在上下文中爲每個對象實例化一些狀態跟蹤實體,所以那裏已經有67k + 67k + 67k,我不會感到驚訝的是,其他輔助對象也會一起創建。 EF在延遲查詢模式下工作,直到您調用SaveChanges這就是OOM發生的原因時,纔會執行實際工作。 – 2011-05-12 16:36:33
我有類似的問題。不清楚應該如何改變片段。很高興看到原始問題的更新。我確實有現有的代碼。在循環之後立即添加foreach循環和SaveChanges。不清楚是否在循環中包含SaveChanges,是否始終清楚通過添加的內容。添加 – MicMit 2012-06-12 23:33:54