liveBook · Manning

One-to-many relationship

As explained in ASP.NET Core in Action, 3e

A many-to-one relationship is an association in which multiple instances of one entity type are associated with a single instance of another entity type.

A one-to-many relationship connects one recipe with many ingredients. From the ingredient’s perspective, it is many-to-one: each ingredient belongs to one recipe. EF Core maps this relationship between application entities and database tables. section 12.1.4

Recognize the relationship through these parts:

  • Recipe exposes an ICollection<Ingredient>, representing the many side. section 12.2.2
  • Ingredient contains RecipeId, a foreign key pointing to the Recipe primary key. section 12.2.2
  • EF Core uses the model to create the database structure and generate SQL for creating, reading, updating, and deleting entities. section 12.1.4

Recipe ingredients

A recipe such as fish pie can contain several ingredients, while each ingredient row belongs to that recipe. Identical ingredients in different recipes remain separate instances: changing lemon quantity in lemon chicken does not change fish pie. section 12.1.4

Listing 12.2 Defining the EF Core entity classes
public class Recipe
{
    public int RecipeId { get; set; }
    public required string Name { get; set; }
    public TimeSpan TimeToCook { get; set; }
    public bool IsDeleted { get; set; }
    public required string Method { get; set; }
    public required ICollection<Ingredient> Ingredients { get; set; }   #1
}
public class Ingredient
{
    public int IngredientId { get; set; }
    public int RecipeId { get; set; }
    public required string Name { get; set; }
    public decimal Quantity { get; set; }
    public required string Unit { get; set; }
}

Inspect the C# entity classes showing the collection navigation property and foreign-key property. section 12.2.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains collection and foreign-key conventions, but defers broader convention details and customization to documentation.
Examples
Uses recipes, ingredients, fish pie, lemon chicken, and separate ingredient instances to demonstrate relationship behavior.
What it assumes
Defines primary keys and foreign keys while working from C# entity classes and an application DbContext.
What you can do after
Build entity classes that let EF Core map one recipe to many ingredients through a collection and foreign key.
How it connects
Connects entity classes, collection navigation properties, primary keys, foreign keys, database tables, and DbContext.

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 ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.