SkillPilotAI

Relationships

Relationships tell EF Core how entities connect: one-to-many, one-to-one and many-to-many. Get them right and the database enforces foreign keys for you; get them wrong and you save orphan rows or lose order history on delete.

52.1 The problem: CustomerId is just an int

  • Order has an int CustomerId but nothing in the model says it points to Customer.
  • So the Orders table gets no foreign key constraint and an order for customer 99 (who does not exist) saves fine.
  • Orphan orders like this silently break reports.
C#
public class Order{    public int Id { get; set; }    public decimal Total { get; set; }    public int CustomerId { get; set; }} // Program.csdb.Customers.Add(new Customer { Name = "Asha" });db.Orders.Add(new Order{    Total = 1899, CustomerId = 99});db.SaveChanges();
Output
$ dotnet runOrder 1 -> CustomerId 99CREATE TABLE "Orders" (    "Id" INTEGER NOT NULL ... PRIMARY KEY AUTOINCREMENT,    "Total" TEXT NOT NULL,    "CustomerId" INTEGER NOT NULL);
Why there was no error
  1. 1.CustomerId = just an int: no idea of a relation

  2. 2.No foreign key: the DB does not check

  3. 3.Orphan order: customer 99 doesn't exist

Fix: a navigation property

52.2 One-to-many with navigation properties

  • Collection navigation: Customer.Orders (List<Order>).
  • Reference navigation: Order.Customer.
  • CustomerId is recognised as the foreign key by its name.
  • Now the schema has a FOREIGN KEY plus an index, and the customer 99 order fails with SQLite Error 19.
C#
public class Customer{    public int Id { get; set; }    public string Name { get; set; } = "";    public List<Order> Orders { get; } = [];} public class Order{    public int Id { get; set; }    public decimal Total { get; set; }    public int CustomerId { get; set; }    public Customer? Customer { get; set; }}
Output
CREATE TABLE "Orders" (    ...    "CustomerId" INTEGER NOT NULL,    CONSTRAINT "FK_Orders_Customers_CustomerId"      FOREIGN KEY ("CustomerId")      REFERENCES "Customers" ("Id") ON DELETE CASCADE);CREATE INDEX "IX_Orders_CustomerId" ON "Orders" ("CustomerId"); $ dotnet run -- orphanDbUpdateException: An error occurred while saving the entity changes.  SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.

52.3 Saving through a navigation

  • Add orders to asha.Orders and never set CustomerId.
  • SaveChanges inserts the customer first, then fills its new Id into both orders.
C#
var asha = new Customer { Name = "Asha" };asha.Orders.Add(new Order { Total = 1899 });asha.Orders.Add(new Order { Total = 399 });db.Customers.Add(asha);db.SaveChanges(); foreach (var o in db.Orders)    Console.WriteLine("Order {0}: Customer {1}",        o.Id, o.CustomerId);
Output
$ dotnet run -- saveOrder 1: Customer 1Order 2: Customer 1

52.4 One-to-one: Customer and Address

  • Customer has an Address reference; Address holds the CustomerId foreign key, so Address is the dependent side.
  • EF gives CustomerId a UNIQUE index: one customer can have only one address.
  • Adding a second (Delhi) address for the same customer fails with UNIQUE constraint failed.
C#
public class Customer{    // Id, Name, Orders    public Address? Address { get; set; }} public class Address{    public int Id { get; set; }    public string City { get; set; } = "";    public int CustomerId { get; set; }    public Customer? Customer { get; set; }}
Output
CREATE UNIQUE INDEX "IX_Addresses_CustomerId"    ON "Addresses" ("CustomerId"); $ dotnet run -- addressAddress -> CustomerId 1DbUpdateException: An error occurred while saving the entity changes.  SqliteException: SQLite Error 19:  'UNIQUE constraint failed: Addresses.CustomerId'.

52.5 Many-to-many: Product and Category

  • A collection on both sides (Product.Categories, Category.Products) tells EF this is many-to-many.
  • EF creates a join table CategoryProduct whose primary key is both ids together.
C#
public class Product{    public int Id { get; set; }    public string Name { get; set; } = "";    public List<Category> Categories { get; }        = [];} public class Category{    public int Id { get; set; }    public string Name { get; set; } = "";    public List<Product> Products { get; } = [];}
Output
CREATE TABLE "CategoryProduct" (    "CategoriesId" INTEGER NOT NULL,    "ProductsId" INTEGER NOT NULL,    CONSTRAINT "PK_CategoryProduct"      PRIMARY KEY ("CategoriesId", "ProductsId"),    CONSTRAINT "FK_CategoryProduct_Categories_CategoriesId" ...    CONSTRAINT "FK_CategoryProduct_Products_ProductsId" ...); $ dotnet run -- categories# Steel Bottle: Kitchen, Sale# Pressure Cooker: KitchenKitchen: Steel Bottle, Pressure CookerBottle categories: 2

52.6 How EF finds a relationship

Relationship discovery by convention
  1. 1.Find navigations: Orders, Customer

  2. 2.Find the foreign key by name: CustomerId

  3. 3.Required or optional: int vs int?

  4. 4.Delete behavior: required = Cascade

All by convention, override with the Fluent API

RelationshipModelWhat EF creates
1-NList<Order> on Customer + CustomerId on OrderFK + normal index
1-1Address reference + CustomerId on AddressFK + UNIQUE index
N-NCollections on both sidesJoin table with composite PK
N-N with extra dataJoin entity (OrderItem)Two 1-N relationships

52.7 Cascade delete and the Fluent API

  • A required relationship defaults to ON DELETE CASCADE: deleting Asha also deleted all her orders.
  • For a shop, order history is accounting / GST data and must not disappear.
  • Fix in OnModelCreating: HasOne / WithMany / HasForeignKey / OnDelete(DeleteBehavior.Restrict).
  • Now deleting a customer who has orders throws a foreign key error, so the history is safe.
C#
var customer = db.Customers.First();db.Customers.Remove(customer);db.SaveChanges(); Console.WriteLine(    $"Customers: {db.Customers.Count()}");Console.WriteLine(    $"Orders: {db.Orders.Count()}");
Output
$ dotnet run -- deleteCustomers: 0Orders: 0
C#
protected override void OnModelCreating(    ModelBuilder modelBuilder){    modelBuilder.Entity<Order>()        .HasOne(o => o.Customer)        .WithMany(c => c.Orders)        .HasForeignKey(o => o.CustomerId)        .OnDelete(DeleteBehavior.Restrict);}
Output
CONSTRAINT "FK_Orders_Customers_CustomerId"  FOREIGN KEY ("CustomerId")  REFERENCES "Customers" ("Id") ON DELETE RESTRICT $ dotnet run -- deleteDbUpdateException: An error occurred while saving the entity changes.  SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.

52.8 IEntityTypeConfiguration

  • With 20 entities OnModelCreating gets very long.
  • Put each entity's Fluent API in its own class implementing IEntityTypeConfiguration<T>.
  • ApplyConfigurationsFromAssembly finds and applies all of them in one line; the result is the same Restrict.
C#
public class OrderConfiguration    : IEntityTypeConfiguration<Order>{    public void Configure(        EntityTypeBuilder<Order> builder)        => builder.HasOne(o => o.Customer)            .WithMany(c => c.Orders)            .HasForeignKey(o => o.CustomerId)            .OnDelete(DeleteBehavior.Restrict);}// ShopContext.csprotected override void OnModelCreating(    ModelBuilder builder)    => builder.ApplyConfigurationsFromAssembly(        typeof(ShopContext).Assembly);

52.9 Common mistakes

  • Direct many-to-many between Order and Product: the auto join table has only two ids, so there is no place for Quantity or UnitPrice (2 pressure cookers?).
  • Fix: a join entity OrderItem with OrderId, ProductId, Quantity and UnitPrice = two one-to-many relationships.
  • Thinking a navigation property is a column: only the FK (CustomerId) is stored; Orders / Customer are C# objects EF fills in.
  • Expecting navigations to load by themselves: you need Include or a projection (querying video).
C#
public class OrderItem{    public int Id { get; set; }    public int OrderId { get; set; }    public Order? Order { get; set; }    public int ProductId { get; set; }    public Product? Product { get; set; }    public int Quantity { get; set; }    public decimal UnitPrice { get; set; }}// Order: List<OrderItem> Items// Product: List<OrderItem> OrderItems

52.10 Rules for relationships

  1. Keep an explicit FK property (CustomerId) and navigations on both sides.
  2. Initialize collection navigations with an empty list.
  3. Choose the delete behavior with care: Restrict for important data.
  4. Many-to-many with extra data: build a join entity.
  5. Keep configuration in IEntityTypeConfiguration classes.

52.11 Interview tips

  • I keep navigation properties plus a FK property, so EF understands 1-N, 1-1 and N-N by convention.
  • Where the default is not enough I use HasOne / WithMany / HasForeignKey / OnDelete in IEntityTypeConfiguration classes.
  • 1-1 gets a unique index on the FK; N-N gets an automatic join table.
  • A required relationship cascades on delete by default, so I use Restrict for important data like orders.