views:

539

answers:

1

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 occassions 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??

+4  A: 

You have two choices:

  • either you let the database handle the primary key, by specifying the VehicleID as INT IDENTITY(1,1) - in that case, SQL Server will automagically assign unique and individual numbers, and EF will be fine with that
  • or you handle it yourself, e.g. you have to find a way in your app to come up with unique vehicle ID numbers.

EF 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

marc_s
and if you handle yourself, you need to design around possible problems with multiple users insterting at the same time. I far prefer to have an autogenerated value.
HLGEM
Yes, absolutely - that's why it's really best left to the database to make sure ID's are unique!
marc_s
Thanks - yes the problem was that I had not set the identity column in the db
Calanus