liveBook · Manning

Primary key

As explained in .NET in Action, Second Edition

A primary key is a column or set of columns whose values uniquely identify rows in a database table.

A primary key is a column or set of columns whose values uniquely identify rows. In an EF Core code-first model, an entity property named Id becomes the key by convention. section 5.2

EF Core key configuration follows two practical paths:

  • Use an Id property, which EF Core recognizes as the primary key when building the table. section 5.2
  • Mark another property, such as ISBN, with the [Key] attribute when it should identify rows instead. section 5.2
  • Include the entity in a DbContext so EF Core relates the class to a database table and generates the key column. section 5.2

Book entity

A Book class with an int Id property maps to a Books table whose Id column is the primary key. Adding several books and ordering by b.Id demonstrates using the key to distinguish and retrieve rows. section 5.2

Listing 5.2 Book class to represent a book in the Manning catalog
namespace ManningBooks;
  
public class Book
{
  public int Id { get; set; }          #1
  public string Title { get; set; }
}

Inspect the Book entity declaration and its convention-based Id key. section 5.2

How .NET in Action, Second Edition covers it

How deep it goes
Explains convention-based and attribute-based configuration, stopping short of deeper database key behavior.
Examples
Uses a Book entity, a generated Books table, an Id property, and ISBN configured with Key.
What it assumes
Assumes familiarity with C# classes and properties while introducing entities, DbContext, and code-first mapping.
What you can do after
Apply it via EF Core by following naming conventions or annotating a different identifying property.
How it connects
Connects primary keys with EF Core, code-first models, entities, DbContext, and database tables.

Also explained in

Compare how 21 books explain primary key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.