New Entity Framework Object - Primary Key Issues

My database has a Vehicle table with a primary key. I create a new Vehicle object using

 new Vehicle(); 

and update vehicle properties accordingly.

When i try to do

 genesisContext.Vehicles.AddObject(vehicle); 

The first time the table is successfully updated and the primary key is 0. In all subsequent cases, I get an error when the key is not unique

Violation of PRIMARY KEY 'VEHICLES_PK' constraint. Cannot insert duplicate key in object 'dbo.Vehicles'. \ R \ nThe application was terminated.

(presumably because the primary key set by EF is still 0)

I was aware that EF intelligently designed primary keys, so why is this happening?

+4
sql-server entity-framework
source share
2 answers

You have two options:

  • or you allow the database to process the primary key by specifying VehicleID as INT IDENTITY(1,1) - in this case, SQL Server will automatically assign unique and individual numbers, and EF will be fine with this
  • or you handle it yourself, for example. You must find a way in your application to come up with unique vehicle identification numbers.

EF out of the box has nothing to magically distribute unique numbers for primary keys - if you think it was a misconception.

Mark

+9
source share

You can assign a new identifier to SavingChanges ObjectContext events

 objectContext.SavingChanges += new EventHandler(objectContext_SavingChanges); 
+1
source share

All Articles