Closed tikhomirovp closed 2 years ago
@tikhomirovp This is a case where a full DetectChanges is needed for correct behavior. However, it may be a place where we can in the future enhance local change detection to be sufficient.
With full DetectChanges
like so:
context.Attach(many);
many.One = one;
context.ChangeTracker.DetectChanges();
many.One = null;
context.ChangeTracker.DetectChanges();
context.SaveChanges(); // the many entity is not saved
the sequence of events is:
Added
state since it's PK has not been set.Added
state for the same reason. At this point, the tracked entities are:OneToMany_Many {Id: -2147482647} Added
Id: -2147482647 PK Temporary
OneId: -2147482647 FK Temporary
One: {Id: -2147482647}
OneToMany_One {Id: -2147482647} Added
Id: -2147482647 PK Temporary
Collection: [{Id: -2147482647}]
OneToMany_One {Id: -2147482647} Added
Id: -2147482647 PK Temporary
Collection: []
In your second example, the change to set the navigation property to null is never seen by EF, and hence there are no changes of state.
In the current code base, local DetectChanges is sufficient for this case; will add a test.
We have a similar descendant from the DbContext:
In the program, we are trying to create an entity as follows:
Current behavior: The entity 'Many' is not saved, the entity 'One' is saved.
Expected behavior: The entity 'Many' is saved, the entity 'One' is not saved.
If you do not explicitly detect change after changing the reference property 'One', everything works as expected:
This behavior is reproduced in version 5.0.12.