Edit: GOT IT! Thanks for your help people :) I posted the "solution" at the end, altough I don't know if it'll help anyone, it was mostly due to bad design on my part..
I'm getting a DbUpdateException when trying to .SaveChanges()
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
InnerException
is:
Violation of PRIMARY KEY constraint « PK_ProduitDepot_1 » ... Cannot insert duplicate key in object Produit-Depot ..
Here's some code I use to see which entities should get saved:
Dim allEntries = MyContext.ChangeTracker.Entries
Dim unchangedEntities As New Dictionary(Of Object, EntityState)
For Each entry As DbEntityEntry In allEntries
Dim NotUnchangedEntity = entry.Entity
If MyContext.Entry(NotUnchangedEntity).State <> EntityState.Unchanged Then
unchangedEntities.Add(entry.Entity, MyContext.Entry(entry.Entity).State)
End If
Next
MyContext.Database.Log = AddressOf Console.WriteLine
context.SaveChanges()
I see in debugging mode that unchangedEntities is empty.
Is there something I'm missing about EF? I don't understand why there would be any SQL executed at all if there's only Unchanged entities in my context's cache...
The table Produit-Depot is a junction table with a * to * relation, so EF hasn't created a class for that table (It's a Database first project)
Let me know if there's anything unclear.
Solution
Interesting part:
As Ivan Stoev pointed out, as the error message was about a junction table (which has no class associated to it, as EF didn't create any when generating my Model), those entitie weren't listed in the the ChangeTracker.Entries
. That's why I believed all the entities were at Unchanged state.
Probably unhelpful part:
I solved my problem with an addition include, using Context.Person.Include("Cars.Wheels")
(made up names, but you get the idea). I used to have only Context.MyEntity.Include("Cars")
and somehow assign my Cars' Wheels
navigation property manually later, using FK's.. This is where the issue came from.