Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Subset Relationships (a.k.a. Extension Tables) - Entity Framework Core

RSS
Modified on Wed, Nov 10, 2021, 7:43 AM by Administrator Categorized as EF Core

Overview

A subset relationship between two tables is where every "A" is a "B", but not every "B" is an "A". One example is the relationship between Boats and Vehicles. (Every boat is a vehicle, but not every vehicle is a boat.) This article outlines how to code such a relationship in Entity Framework Core.

The cardinality of such relationship is a one-to-zero-or-one. The subset table has also been called an "extension table", as it extends the superset table with additional details.

Sample Code

Superset Class

Notes
  • There is no backing field for the navigation property.

public class Vehicle
{
    [Key]
    public int Id { get; set; }

    public virtual Boat Boat { get; set; }
}

Subset Class

Notes
  • The primary key on the subset class is a foreign key against the superset class (i.e., on the navigation property).

public class Boat
{
    [Key]
    public int Id { get; set; }
    
    [ForeignKey("Id")]
    public virtual Vehicle { get; set; }

}

Fluent API

Notes
  • Include this in the DbContext class.

protected override void OnModelCreating(ModelBuilder mb)
{
    // ... other code ...
    
        mb.Entity<Boat>()
            .HasOne(x => x.Vehicle)
            .WithOne(x => x.Boat)
            .IsRequired(false)
            .OnDelete(DeleteBehavior.Restrict);

    // ... other code ...
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.