实体框架(EF)OutOfMemoryException

Vla*_*den 5 .net c# entity-framework out-of-memory entity-framework-4

我有来自其他来源的> 67000条记录来到我的系统.将业务规则应用于这些记录后,我必须将它们存储到数据库中.我使用以下代码执行此操作:

        using (var context = new MyEntities())
        {
            var importDataInfo = context.ImportDataInfoes.First(x => x.ID == importId);

            importedRecords.ForEach(importDataInfo.ValuationEventFulls.Add);

            context.SaveChanges();
        }
Run Code Online (Sandbox Code Playgroud)

执行代码后,我收到以下错误(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)
Run Code Online (Sandbox Code Playgroud)

我使用的是EF 4.0.

我的问题是要保存的记录数量有限制吗?保存大量记录的最佳做法是什么(将它们保存在块中?交易怎么样?).

提前谢谢大家.

Chr*_*sic 4

您可能希望一次分批发送大约 1024 条记录的数据。

您可以包装在事务中对记录进行批处理的循环,以便您可以根据需要回滚整个序列。请注意,此事务很可能会升级为分布式事务。

分布式事务只能应用于运行 Microsoft 分布式事务协调器 (MS-DTC) 服务的服务器。在处理分布式事务时,性能会受到显着影响。