エンティティフレームワーク:大規模なデータセットインサートの最適化
大規模なデータセットをエンティティフレームワークに効率的に挿入することは、パフォーマンスに不可欠です。 多数のレコード(たとえば、4000)を使用してを使用する場合、一般的な課題が発生し、デフォルトのトランザクションタイムアウト(10分)を超える可能性があります。 重要なのは、プロセスを大幅に遅くするTransactionScope
への頻繁な呼び出しを避けることです。
SaveChanges()
いくつかの戦略は、バルク挿入速度を劇的に改善できます:
SaveChanges()
に電話してください。
SaveChanges()
SaveChanges()
事前に決められた数のレコード(例えば、100または1000)を呼び出してください。SaveChanges()
SaveChanges()
)は、バルク操作中の効率を高めます。
AutoDetectChangesEnabled = false
次のコードは、バッチとコンテキストのリサイクルを使用した高性能バルクインサートアプローチを示しています:
この例は、1000の記録ごとにコミットし、各コミット後にコンテキストを再現します。 実験では、異なる
using (TransactionScope scope = new TransactionScope()) { MyDbContext context = null; try { context = new MyDbContext(); context.Configuration.AutoDetectChangesEnabled = false; int count = 0; foreach (var entityToInsert in someCollectionOfEntitiesToInsert) { ++count; context = AddToContext(context, entityToInsert, count, 1000, true); // Commit every 1000 records } context.SaveChanges(); } finally { context?.Dispose(); } scope.Complete(); } private MyDbContext AddToContext(MyDbContext context, Entity entity, int count, int commitCount, bool recreateContext) { context.Set<Entity>().Add(entity); if (count % commitCount == 0) { context.SaveChanges(); if (recreateContext) { context.Dispose(); context = new MyDbContext(); context.Configuration.AutoDetectChangesEnabled = false; } } return context; }
以上が大規模なデータセットのエンティティフレームワークインサートを最適化するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。