Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New object in Entity Framework - problems with primary key

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

like image 296
Calanus Avatar asked Dec 30 '22 18:12

Calanus


1 Answers

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

like image 70
marc_s Avatar answered Jan 01 '23 06:01

marc_s