Autonumber with Entity Framework
Posted
by dcompiled
on Stack Overflow
See other posts from Stack Overflow
or by dcompiled
Published on 2010-06-10T05:05:39Z
Indexed on
2010/06/10
5:13 UTC
Read the original article
Hit count: 906
I want to loop through a collection of objects and add them all to a table. The destination table has an auto-increment field. If I add a single object there is no problem. If I add two objects both with the primary key of zero, the entity framework fails. I can manually specify primary keys but the whole point of trying the EF was to make life easier not more complicated. Here is the code and the exception received follows.
foreach (Contact contact in contacts)
{
Instructor instructor = InstructorFromContact(contact);
context.AddToInstructors(instructor);
}
try
{
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Objects.ObjectContext.SaveChanges()
at DataMigration.Program.CopyInstructors() in C:\Projects\DataMigration\Program.cs:line 52
© Stack Overflow or respective owner