Reputation: 26257
In my database I have a Vehicle
table with a primary key. I am creating a new Vehicle
object using
new Vehicle();
and updating the properties of vehicle appropriately.
When I try to do a
genesisContext.Vehicles.AddObject(vehicle);
The first time the table is successfully updated and the primary key is 0. On all subsequent occasions I get an error saying that the key is not unique
Violation of PRIMARY KEY constraint 'VEHICLES_PK'. Cannot insert duplicate key in object 'dbo.Vehicles'.\r\nThe statement has been terminated.
(presumably because the primary key set by the EF is still 0)
I was under the understanding that the EF intelligently works out primary keys so why is this happening??
Upvotes: 4
Views: 5817
Reputation: 11
You can assign the new id on SavingChanges
events of ObjectContext
objectContext.SavingChanges += new EventHandler(objectContext_SavingChanges);
Upvotes: 1
Reputation: 754230
You have two choices:
INT IDENTITY(1,1)
- in that case, SQL Server will automagically assign unique and individual numbers, and EF will be fine with thatEF out of the box has nothing in it to magically dispense unique numbers for primary keys - if you thought that, it was a misconception.
Marc
Upvotes: 9