liveBook · Manning

One-to-many relationship

As explained in .NET in Action, Second Edition

A one-to-many relationship associates one instance of a principal entity with multiple instances of a dependent entity.

A one-to-many relationship associates one principal entity with multiple dependent entities. In EF Core, a collection navigation property such as Book.Ratings signals that one Book can have many Rating records. section 5.2.3

A practical EF Core model uses:

  • A principal entity with a collection navigation property, such as List<Rating> Ratings. section 5.2.3
  • A dependent entity with a foreign key, such as Rating.BookId, and a reference navigation property, such as Rating.Book. section 5.2.3
  • EF Core conventions that match BookId to Book.Id and generate the related tables and foreign keys. section 5.2.3

Persisting and loading ratings

Create a Book, add several Rating objects to its Ratings collection, add the Book to the context, and call SaveChanges. Querying with Include(b => b.Ratings) loads each book together with its ratings for display. section 5.2.3

Listing 5.9 One-to-many relationship with Book as the parent and Rating as the child
class Book {
  public int Id {get;set;}
  public List<Rating> Ratings
    {get;}
}
class Rating
{
  public int Id {get;set;}
  public int BookId {get;set;}
  public Book Book {get;}
}

The focused entity listing shows the principal collection, dependent foreign key, and navigation property together. section 5.2.3

How .NET in Action, Second Edition covers it

How deep it goes
Explains entity properties, convention-based foreign keys, generated tables, persistence, and loading, but does not detail explicit configuration.
Examples
Uses Book and Rating classes, ratings with stars and comments, EF Core persistence, and Include-based console output.
What it assumes
Assumes familiarity with C# classes and EF Core contexts while teaching relationship conventions through concrete entities.
What you can do after
Builds and tests a one-to-many EF Core model that saves dependent entities and retrieves them with their principal.
How it connects
Connects principal and dependent entities, navigation properties, foreign keys, relational tables, and eager loading.

Also explained in

Compare how 12 books explain one-to-many relationship →

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.