Irish Yobbo
Irish Yobbo

Reputation: 433

Choosing primary key value in LINQ to SQL

I'm creating an asp.net site that used linq to sql to create, edit and delete cars and race results. Each car has it's own number which has been set as the primary key. Each result has a result number, and there is a many-to-one relationship between the results and cars.

To create a new car object I use the Car DataContext, which automatically updates the database as requires using the DataContext.SubmitChanges() function. However it won't update the primary key, instead choosing a new one by incrementing the largest current value.

Since each car's number is important, is there any way to choose the primary key value using this method? Or should I make the car ID separate and use a separate piece of code to make sure the ID is unique?

Upvotes: 2

Views: 580

Answers (1)

nick_w
nick_w

Reputation: 14938

As you aluded to in your question, keeping the Car number separate from its Id is the way to go. The reason for this is that it is possible that two cars could at some point have the same number, in addition to the fact that the database is choosing its own value for the Id anyway.

Just add another field to your Car table to record its number and you should be good to go.

See Update primary key value using entity framework for more information.

Upvotes: 2

Related Questions