liveBook · Manning

Foreign key

As explained in .NET in Action, Second Edition

A foreign key is a relational-database column or set of columns whose values reference a key in another table.

A foreign key is a column or set of columns whose values reference a key in another table. In EF Core, Rating.BookId references Book.Id, linking each dependent Rating to its principal Book. section 5.2.3

Use foreign keys to model these relationship patterns:

  • One-to-one: a Book can optionally have one Rating; EF Core does not automatically enforce database-level uniqueness for this relationship. section 5.2.3
  • One-to-many: a Book has a collection of Ratings, with each Rating carrying BookId. section 5.2.3
  • Many-to-many: EF Core uses a join table because one foreign-key column cannot represent both directions. section 5.2.3
Listing 5.8 One-to-one relationship with Book as the parent and Rating as the child
class Book {
  public int Id {get;set;}
  public Rating? Rating {get;}
}
class Rating
{
  public int Id {get;set;}
  public int BookId {get;set;}
  public Book Book {get;set}
}

The C# model shows the foreign-key property beside navigation properties, allowing EF Core conventions to establish the relationship. section 5.2.3

How .NET in Action, Second Edition covers it

How deep it goes
Explains convention-based mapping, navigation properties, relationship cardinality, and deferred database-level one-to-one enforcement.
Examples
Uses Book, Rating, and Tag entities, plus generated tables and C# queries that save and print ratings.
What you can do after
Apply it via EF Core conventions to model and query related Book and Rating entities.
How it connects
Connects primary keys, navigation properties, one-to-one relationships, one-to-many relationships, many-to-many relationships, and join tables.

Also explained in

Compare how 18 books explain foreign 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.