ASP.NET MVC: Why do all my tables need a primary key ....

  • Thread starter Thread starter Jamin2112
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
Physics news on Phys.org
Primary keys are often needed to insure uniqueness of records in a database. They also allow you to reference, update or delete a record.

So if those actions are needed then that explains the need for a primary key.
 
I guess my big question is, how does my ASP.NET project know how to recreate the database after I drop it? Is there a 1-to-1 mapping between the C# code that models a database and the SQL query that would generate that database? Or when I use the ADO.NET Entity Data Model to create the model, does it write a query behind the scenes?
 
Any software which generates code for handling data will require each database table involved to have a primary key, which is usually an integer that acts as a unique identifier for each record. This key is needed because the records themselves may contain identical data, making them otherwise impossible to distinguish. In order to update an existing record, it must be possible to know beyond a shadow of a doubt which record should be updated.

If there were not primary key on a table, an update request, if finding two identical records, would have to make an arbitrary decision: 1) update ALL records matching the criterion, or 2) update the FIRST RECORD FOUND to match the criterion (and you would not know which record it found first because you don't know exactly how the database is searching for the records). The use of a primary key avoids such ambiguities.