liveBook · Manning

Composite key

As explained in Building Web APIs with ASP.NET Core

A composite primary key is a primary key formed from multiple columns whose combined values uniquely identify a record.

A composite primary key combines multiple columns so their values uniquely identify a record. In EF Core, it commonly identifies rows in many-to-many junction tables. section 4.3.3

Configure composite keys in an EF Core model by:

  • Adding [Key] properties to each participating identifier, such as BoardGameId and DomainId. section 4.3.3
  • Defining the combined key with HasKey in OnModelCreating, because composite-key support requires Fluent API configuration. section 4.3.3
  • Applying the pattern to junction entities such as BoardGames_Domains and BoardGames_Mechanics, where each mapped relationship should be unique. section 4.3.3
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
 
modelBuilder.Entity<BoardGames_Domains>()
.HasKey(i => new { i.BoardGameId, i.DomainId });
 
modelBuilder.Entity<BoardGames_Mechanics>()
.HasKey(i => new { i.BoardGameId, i.MechanicId });
}

The configuration combines BoardGameId with DomainId or MechanicId inside OnModelCreating. section 4.3.3

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains annotations and Fluent API configuration, then stops before detailed query or migration verification.
Examples
Uses BoardGames_Domains and BoardGames_Mechanics with paired identifiers and HasKey expressions.
What it assumes
Assumes basic entity modeling and EF Core, while introducing Fluent API configuration for composite keys.
What you can do after
Build it from scratch by defining junction entities and configuring their combined keys with EF Core Fluent API.
How it connects
Connects composite keys with EF Core, Fluent API, many-to-many relationships, junction tables, navigation properties, and foreign keys.

Also explained in

Compare how 8 books explain composite key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.