I have been trying to find newly added entities on a context by using TryGetObjectByKey:
Dim ObjectFound As Boolean = Context.TryGetObjectByKey(entityKey, obj)
I found that TryGetObjectByKey always failed, even when I knew that the entity I was looking for had been added to the context. The entity in question uses email address as the primary key, and that email address is provided through the constructor for the entity (it is not generated by the DB):
Public Class Customer
Private _email as string
Public Sub New (Email as string)
'Email is the primary key in the DB and the entity key in EF4.
'It is not generated by the DB.
_email = Email
End Sub
End Class
After further investigation I found that the EntityKeys for all of the added entities had no values, and their IsTemporary flag was set to true. TryGetObjectByKey was failing because the EntityKey for the added objects was not yet set.
I was originally under the impression that the EntityKey would be generated immediately upon calling AddObject if the EntityKey was not generated by the DB. So, two questions:
1) Should I expect all newly added entities to have temporary EntityKeys?
2) If #1 is true, how can I find newly added entities by primary key?
MSDN states the following:
Only after SaveChanges (and the corresponding Insert statement) an EntityKey is created.