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??
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With