EF4 SaveChanges如何避免内存不足异常

时间:2012-06-13 00:04:14

标签: entity-framework-4 savechanges

现有片段

foreach (var ownerCandidates in ownerToCandidatesDictionary)
  {
    foreach (var candidate in ownerCandidates.Value)
    {
       transactionEntities.AddToSomeEntity(someObject)
    }
  }
                transactionEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

重写

    int i = 0 ; 
    foreach (var ownerCandidates in ownerToCandidatesDictionary)
    {
         foreach (var candidate in ownerCandidates.Value)
         {
             transactionEntities.AddToSomeEntity(someObject)
          }
          if ( i++ % 1000 == 0 ) 
          {
               transactionEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
          } 
    }

transactionEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

在程序成功终止的情况下为我们提供相同的功能?我关注的是我们继续添加,循环中的SaveChanges只能使用自之前的SaveChanges以来添加的内容。我们这里有分批储蓄吗?如果不是如何改变原始片段以避免

12/06/2012 7:50:37 PM : System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Data.Mapping.Update.Internal.Propagator.Project(DbProjectExpression node, PropagatorResult row, TypeUsage resultType)
   at System.Data.Mapping.Update.Internal.Propagator.Visit(DbProjectExpression node)
   at System.Data.Common.CommandTrees.DbProjectExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
   at System.Data.Mapping.Update.Internal.Propagator.Propagate(UpdateTranslator parent, EntitySet table, DbQueryCommandTree umView)
   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)

1 个答案:

答案 0 :(得分:6)

如果在之前的SaveChanges()之后没有对实体集进行更改,则后续调用SaveChanges()将不会产生任何影响。在SaveChanges()之后,数据库中的内容是新批处理。批处理是在使用EntityFramework进行大量插入时克服OutOfMemoryException的选项。实际上SaveChanges()应该只调用一次,但在你的情况下,因为数据很大,所以必须将其分成批次。

同时,在批量添加实体以获得显着的性能改进时,通过将AutoDetectChangesEnabled设置为false,暂时禁用自动检测更改。 Here is the info context.Configuration.AutoDetectChangesEnabled = false;