Paraphrasing from this MSDN documentation ...
An INSERT statement is generated by the Entity Framework and executed on the data source when SaveChanges is called on the ObjectContext.
If the INSERT operation succeeds, server-generated values are written back to the ObjectStateEntry. When AcceptChanges is called automatically at the end of the SaveChanges execution, a permanent EntityKey is computed by using the new server-generated values.
This does not seem to be occurring in my code. When I call ObjectContext.SaveChanges(), an UpdateException is thrown with the InnerException.Message: "duplicate key value violates unique constraint student_term_data_pkey":
using (DataAccessLayerEntities context = new DataAccessLayerEntities())
{
StudentTermData mostCurrent = new StudentTermData();
// Set foreign keys.
mostCurrent.StudentId = studentId;
mostCurrent.TermId = currentTerm.Id;
// Set non-nullable properties.
mostCurrent.SponsorCode = string.Empty;
mostCurrent.AdmissionNumber = string.Empty;
mostCurrent.Expiration = string.Empty;
// Add student term data to object set.
context.StudentTermDatas.AddObject(mostCurrent);
// UpdateException occurs here.
context.SaveChanges();
}
I have verified that StudentTermData.Id is marked as an EntityKey in my Entity data model. Any ideas / suggestions are very much appreciated.