Why is inserting entities in EF 4.1 so slow compared to ObjectContext?
As already indicated by Ladislav in the comment, you need to disable automatic change detection to improve performance:
context.Configuration.AutoDetectChangesEnabled = false;
This change detection is enabled by default in the DbContext
API.
The reason why DbContext
behaves so different from the ObjectContext
API is that many more functions of the DbContext
API will call DetectChanges
internally than functions of the ObjectContext
API when automatic change detection is enabled.
Here you can find a list of those functions which call DetectChanges
by default. They are:
- The
Add
,Attach
,Find
,Local
, orRemove
members onDbSet
- The
GetValidationErrors
,Entry
, orSaveChanges
members onDbContext
- The
Entries
method onDbChangeTracker
Especially Add
calls DetectChanges
which is responsible for the poor performance you experienced.
I contrast to this the ObjectContext
API calls DetectChanges
only automatically in SaveChanges
but not in AddObject
and the other corresponding methods mentioned above. That's the reason why the default performance of ObjectContext
is faster.
Why did they introduce this default automatic change detection in DbContext
in so many functions? I am not sure, but it seems that disabling it and calling DetectChanges
manually at the proper points is considered as advanced and can easily introduce subtle bugs into your application so use [it] with care.
Little empiric test with EF 4.3 CodeFirst:
Removed 1000 objects with AutoDetectChanges = true : 23 sec
Removed 1000 objects with AutoDetectChanges = false: 11 sec
Inserted 1000 objects with AutoDetectChanges = true : 21 sec
Inserted 1000 objects with AutoDetectChanges = false : 13 sec