Setting AutoDetectChangesEnabled
to false
doesn't disable change tracking. (That's what the AsNoTracking()
extension method would do.) It just disables the automatic call of DetectChanges
that would otherwise occur in many DbContext
API methods.
But DetectChanges
isn't the only method that participates in change tracking. However, if you don't call it manually at the right places where it is needed the tracked entity states are incomplete or wrong leading to incorrectly saved data.
In your case the state Added
in the first part of your method
is expected, even with AutoDetectChangesEnabled
set to false
because you only call db.Projects.Add(p)
. (The line is missing in your code btw, but I guess it's just a copy and paste error.) Calling a method from the DbContext
API tracks changes correctly and the states in the tracker will be correct if the state was correct before the call to Add
.
Or in other words: Calling an API method doesn't turn a correct state into a wrong state. But: If AutoDetectChangesEnabled
is false
it also won't turn a wrong state into a correct state which would be the case if AutoDetectChangesEnabled
is true
.
However, in the second part of your method
you are just changing a POCO property value. After this point the change tracker state is wrong (Unchanged
) and without a call to DetectChanges
(manually or - if AutoDetectChangesEnabled
is true
- automatically in ChangeTracker.Entries
or SaveChanges
) it will never be adjusted. The effect is that the changed property value is not saved to the database.
In the last section mentioning the state Unchanged
I'm refering to my own test (and also to what I would expect). I don't know and can't reproduce why you have state Modified
.
Sorry, if this sounds all a bit confusing. Arthur Vickers can explain it better.
I find automatic change detection and the behaviour when disabling it rather difficult to understand and to master and I usually don't touch the default (AutoDetectChangesEnabled
= true
) for any tracked changes that are more complex than the simplest things (like bulk adding entities in a loop, etc.).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…