Prokurors
Prokurors

Reputation: 2548

DbContext.Configuration.AutoDetectChangesEnabled always True VS enabling just before SaveChanges()

I am trying to boost my EF operation performance, and I have found some recommendations regarding DbContext.Configuration.AutoDetectChangesEnabled property a) in some cases to turn off AutoDetectChangesEnabled - this is clear - I am using it for import functions b) but then I have noticed this type of approach with enabling this property only before calling SaveChanges():

DbContext db = new DbContext();
db.Configuration.AutoDetectChangesEnabled = false;

//...some changes to POCO properties

db.Configuration.AutoDetectChangesEnabled = true;
db.SaveChanges();

all the changes seem to be correctly saved to database and it works noticably faster compared to approach where AutoDetectChangesEnabled property is leaved intact.

Question

So I wonder is there a reason to leave AutoDetectChangesEnabled intact? What risks there could be if I disable this property by default and then reenable each time before calling DbContext.SaveChanges?

Related post

This post suggests that there might be reasons to leave AutoDetectChangesEnabled==true, but no clear evidence when and why should do so (ok, it says - do so, if entities are EDITED). Has anybody found out argument for/against this?

EF Code First: is good to call DetectChanges just before SaveChanges?

Upvotes: 3

Views: 820

Answers (1)

mqueirozcorreia
mqueirozcorreia

Reputation: 943

If you look at the documentation Entity Framework Automatic Detect Changes it says:

When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached.

So I think this support the link that you found that if the entity is Edited, with AutoDetectChangesEnabled=true, the change is tracked.

I've been disabling the AutoDetectChangesEnabled for Insert, with great performance improvement.

Upvotes: 1

Related Questions