Entity Framework: Primary key violation
-
I try to add an object to a database, but I get an exception Code:
DataModelContainer cont = new DataModelContainer();
(...)
cont.AddToStudentSet(cont.StudentSet.CreateObject()); cont.SaveChanges();
After running the code twice, I get: Exception: 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. The Id of Student has an AutoIncrement set to TRUE in the database. On the first run a single Student record is created with Id 0. Later, no data is saved to the table at all. The reason of why is it happening seems to be obvious, but it should work anyway. Any help appreciated
Greetings - Jacek
-
I try to add an object to a database, but I get an exception Code:
DataModelContainer cont = new DataModelContainer();
(...)
cont.AddToStudentSet(cont.StudentSet.CreateObject()); cont.SaveChanges();
After running the code twice, I get: Exception: 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. The Id of Student has an AutoIncrement set to TRUE in the database. On the first run a single Student record is created with Id 0. Later, no data is saved to the table at all. The reason of why is it happening seems to be obvious, but it should work anyway. Any help appreciated
Greetings - Jacek
Well, since you already have a student record with an Id of 0, you can't add another one. ID's should not start with 0.
A guide to posting questions on CodeProject[^]
Dave Kreskowiak -
Well, since you already have a student record with an Id of 0, you can't add another one. ID's should not start with 0.
A guide to posting questions on CodeProject[^]
Dave KreskowiakThe scenario was: 1. I had designed tables with an inheritance relationship. 2. Decided that it was not a good idea 3. Removed an inheritance relationship 4. Added required IDs to the tables and set IsIdentity to true. 5. Forgot to set an identity property to "Identity". Well...
Greetings - Jacek