Entity Framework Core Mastery

One-to-Many Relationships & Foreign Keys

1 Views Updated 5/4/2026

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."

Entity Framework Core Mastery
1. Foundations & Architecture
Introduction to Object Relational Mapping (ORM) Entity Framework Core Architecture & Providers Setup and DbContext Integration Code-First vs Database-First Approaches Reverse Engineering Existing Databases (Scaffolding)
2. Code-First Modeling
Entity Conventions & Data Annotations The Fluent API Deep Dive (OnModelCreating) Primary Keys, Composite Keys, & Guids Required Properties & Database Defaults Value Conversions (Enums & Strongly Typed IDs)
3. Relational Architecture
One-to-Many Relationships & Foreign Keys One-to-One Relationships (Dependent Entities) Many-to-Many Relationships & Navigation Properties Owned Entity Types (Value Objects) Table-per-Hierarchy (TPH) Inheritance
4. Data Querying & LINQ
Basic LINQ Queries & IQueryable Execution Tracking vs No-Tracking Queries (Performance) Eager Loading vs Explicit Loading (Include) Lazy Loading Pitfalls & Proxies Client vs Server Evaluation Parsing
5. Manipulating Data (CUD)
Adding, Updating, and Removing Entities The ChangeTracker and Entity States Disconnected Entities in Web APIs Batch Updates and Deletes (.NET 7+)
6. Advanced Performance & Scale
Concurrency Tokens and Optimistic Locking Raw SQL Queries and Views (FromSqlRaw) Compiled Queries for High Throughput Interceptors (Logging & Auditing Data Changes) DbContext Pooling Mechanisms Managing Complex EF Core Migrations (CI/CD)