I have read few articles (article1, article2) about Entity Framework that it calls DetectChanges many times, which makes it very slow when working with large amounts of data.
Can i, for example, disable the autoDetectChanges
when i initialize the context, and just call DetectChanges()
before calling .SaveChanges()
?
Will the context recognize the inserted/changed/deleted entities?
var _dbContext = new ProjectContext();
_dbContext.Configuration.AutoDetectChangesEnabled = false;
// add/edit/delete entities
_dbContext.ChangeTracker.DetectChanges();
_dbContext.SaveChanges();
Should this approach work? or it may create hidden bugs?
One of the main problems that can be resolved by
DetectChanges
is persisting data in EF when we haveManyToMany
relation andAutoDetectChanges=false
.Arthur Vickers defines a rule when
DetectChanges
doesn't need to be called (even not beforeSaveChanges
) in this blog post:Regarding Add and Delete these are "EF code" methods because you either call
Add
orDelete
or you set the state ofcontext.Entry(entity).State
toAdded
orDeleted
. So, if you would just loop through a bunch of entites and add or delete them then you don't need to callDetectChanges
at all.Regarding Edit it is, I believe, a bit more subtle. When you update entities by using either...
...or by using the property API of
DbContext
......then you don't need
DetectChanges
(even not beforeSaveChanges
) either because these are again calls into "EF code".If you just change property values of an entity like...
...then the second rule in the same blog post linked above applies:
And I think you need in fact only one single call to
DetectChanges
beforeSaveChanges
if you just loop through some entities, load them into or attach them to the context and change some (scalar and complex) property values.If you do more complex stuff (maybe relationship changes? or something else?) your approach might not be safe anymore because
AutoDetectChanges
would not be implemented in the way it is and called in many EF methods if it would be only necessary once right beforeSaveChanges
it is mentioned in the same blog post again that
(Highlighting from me)
Unfortunately I don't know an example of code that would show when calling
DetectChanges
at earlier stages than right beforeSaveChanges
is necessary. But because of point 1 above I am sure such examples exist.