Tutorials Entity Framework Core Mastery

One-to-Many Relationships & Foreign Keys

On this page

One-to-Many Relationships & Foreign Keys

The crux of a relational database is establishing relationships between completely separate tables. A One-to-Many relationship is the most widespread pattern: A single Blog can possess many Posts. EF Core manages this via Navigation Properties.

1. Modeling the Navigation Properties

To establish a clean one-to-many relationship, we define properties on BOTH sides of the equation.

public class Blog // The "Principal" Entity (The Parent)
{
    public int Id { get; set; }
    public string Url { get; set; }

    // Collection Navigation Property: A Blog has MANY Posts
    public ICollection<Post> Posts { get; set; } = new List<Post>();
}

public class Post // The "Dependent" Entity (The Child)
{
    public int Id { get; set; }
    public string Title { get; set; }

    // 1. Foreign Key Property (The physical integer stored in SQL Server)
    public int BlogId { get; set; } 

    // 2. Reference Navigation Property (The parent object representation in C# Memory)
    public Blog Blog { get; set; } 
}

2. Fluent API Configuration

While EF Core conventions usually auto-detect the setup above perfectly, relying on magic is dangerous in enterprise environments. We always explicitly document relationships via the Fluent API to prevent accidental schema drift.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>(entity =>
    {
        // Read out loud: "A post HAS ONE attached Blog, 
        // WITH MANY attached Posts belonging to that Blog, 
        // and the physical link exists via the BlogId Foreign Key."
        entity.HasOne(p => p.Blog)
              .WithMany(b => b.Posts)
              .HasForeignKey(p => p.BlogId)
              .OnDelete(DeleteBehavior.Cascade); // What happens if the Parent is deleted
    });
}

3. Delete Behaviors

What happens to the hundred child Posts when an administrator physically deletes the parent Blog from the database?

  • Cascade: The SQL Server violently murders all 100 children automatically. Excellent for preventing orphaned data.
  • Restrict: The database BLOCKS the deletion of the parent and throws a crash error until you manually delete all 100 children first. Highly secure.
  • SetNull: The child posts stay alive in the database, but their BlogId is wiped to NULL, marking them as orphaned. Requires the Foreign Key property to be nullable in C# (int? BlogId).

4. Interview Mastery

Q: "In a deeply nested hierarchy, removing an entity results in EF Core throwing an exception stating 'Introducing FOREIGN KEY constraint may cause multiple cascade paths'. What does this mean and how do we fix it?"

Architect Answer: "This is a native SQL Server restriction, not an EF Core error. If Table A cascades deletes to Table B, and Table A ALSO cascades deletes to Table C, and Table C cascades to Table B... SQL Server panics. When a row in Table A is deleted, the engine doesn't know which cascading path to execute first to kill the row in Table B, fearing a cyclic deadlock. To resolve this, you must analyze your Entity relationships via the Fluent API and explicitly change at least one of the secondary `.OnDelete()` behaviors from `Cascade` to `DeleteBehavior.Restrict` or `NoAction`, forcing the developer to handle the secondary deletion manually in C# code."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Entity Framework Core Mastery
Course syllabus
1. Foundations & Architecture
2. Code-First Modeling
3. Relational Architecture
4. Data Querying & LINQ
5. Manipulating Data (CUD)
6. Advanced Performance & Scale
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details