Updated on Kisan Patel
Problem:
Entity Framework gets slow in long Iteration Loops.
Entity Framework and slow bulk INSERT.
When working with bulk insert you need to use long iteration loops in enity framework like below:
for (int i = 0; i < 10000; i++) { var context = new DbContext(); … add items to the context tables context.SaveChanges(); }
Solution:
the easiest solution is to turn off AutoDetectChangesEnabled
. This confirms that the problem in and of itself is the change tracking in EF on large datasets. Turning off this flag on the context also brings the time down to about 20 seconds and – more importantly - it also works for my DbInitializer since I can simply apply the flag on the existing passed in context:
context.Configuration.AutoDetectChangesEnabled = false; for (int i = 0; i < 10000; i++) { … do the Context.Add() / SaveChanges() here as before }