Unique Constraint Violation when using TrackGraph() and Partial Updates
Hello, I'm getting an error when I attempt to commit a graph that contains a one-to-one mapping, but the error only occurs when I try to do a partial update (only updating changed fields). If I commit using a full update, there is no error.
Disclaimer: I'm using a custom method for the lambda expression in TrackGraph(), so this may not be a typical scenario - not sure. I've developed this method as a general solution for setting foreign key properties in the Change Tracker during the tracking process. Using this method, I only need to set the navigation properties in my code, and everything gets 'fixed up' during the track process.
Exception message: Inner Exception: Cannot insert duplicate key row in object 'dbo.Parents' with unique index 'IX_Parents_ChildId'. The duplicate key value is (1). The statement has been terminated.
Stack trace:
Outer Exception:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.1.GetResult()
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__59.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Microsoft.EntityFrameworkCore.DbContext.
Inner Exception:
at System.Data.SqlClient.SqlCommand.<>c.1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.
Steps to reproduce
I have a demo that reproduces both the successful commit using full update and the error using a partial update. Unfortunately, I'm having difficulty adding it to the issue. It may be a firewall policy on my end or something. Is there an alternative way I can send it to you?
Further technical details
EF Core version: 2.0.0 (also occurred in 1.1.2, so not a regression bug)
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 8.1 IDE: Visual Studio 2017
@johnavery EF already does fix up of FK properties based on navigations, so there shouldn't need to be special code in TrackGraph to handle this. Is there something about the EF behavior that was not working for you?
Beyond this, we'll need some idea of what the code in TrackGraph does in order to be able to dig into this deeper. If you can't post it here, then you can email to me--avickers at the place I work.
EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.
@johnavery Thanks for sending the repro code. There is a lot of custom logic going on, and I'm not sure the real intent behind it all, but the reason that an exception is being thrown is that before calling SaveChanges there is a new (Added) Parent, but this parent still references the original Child, both through navigation property and it's FK. Since the Parent-Child relationship is 1:1 it means that the FK maps to a column with a unique constraint--only one Parent can reference any one child, and therefore every parent must have a different value for it's Child FK. So then there is an exception thrown from the database when the new Parent is inserted since it has the same FK as the already existing Parent. You'll need to update the logic that is creating these relationships to be consistent before SaveChanges will be able to succeed.
I also noticed that the entity states often don't match the changes made to the entity. For example, there are entities for which an FK has changed, but these entities are still in the Unchanged state, rather than in the Modified state, so changes to those FK will not happen in the database. Again, I'm not sure whether this is intended or not, but a better practice might be to keep the graph in a consistent state--if the FK shouldn't change then don't have it change, rather than having it change but then marking the entity as Unchanged.
Hope this helps a bit.
@ajcvickers Thanks for the review. I agree with your comment about the added Parent referencing the original child, however, you may not have noticed that the modified Parent that originally referenced that Child has been updated to reference an added Child in the same graph. So, I would expect that the topological sort would recognize that and issue the update to the modified Parent first, to then allow the insert of the added Parent without violating the unique constraint.
This is in fact what does happen in the _Success test - the queries are issued in the correct order and the transaction succeeds. It is only in the _Fail test that the issue is exposed - when I attempt to do a partial update (only update the modified columns), rather than a full update (update all columns), as in the _Success test.
To achieve the partial update in the _Fail test, during the TrackGraph process, instead of marking the state of an entity that has changes as 'Modified', I instead mark it as 'Unchanged' initially, and then I go ahead in the custom logic and set the PropertyEntry.IsModified = true for each property that has changed. Interestingly, the net effect of setting IsModified = true is that the EntityState then changes from 'Unchanged' to 'Modified', but somehow the underlying EF code knows to only issue updates to the modified properties (at least this is the behavior I have observed so far).
As far as the inconsistent states - you are correct, this was a bug in my repro code. I have since fixed the issue and re-posted my sample to the share you accessed to get my original code.
You should have received another email notifying you of the new upload. If you wouldn't mind kindly reviewing it again, I would greatly appreciate it. Thanks!
Hi, I see that this issue is in the closed state. I've sent a new repro solution for review. Is anyone currently working on this issue? I just want to make sure I'm not waiting for a reply to an issue that is not being worked on. Thanks!
@johnavery I plan to take another look. Just to set expectations, the original repro code did not demonstrate any issue in EF Core, and my investigation of the new code will be along the same lines--see if EF is working as expected in your application code. I don't intend to dig deep into your application logic and try to find bugs in that.
Understood. Thank you!
@johnavery With the new code, I still see that both Parents reference the same Child, the problem seems the same as before. I can't see anything here that EF is doing wrong--I think the code you have is still putting things into an inconsistent state.
