Relationships in Entity Framework Code First

Overview

Establishing various relationships (one-to-one, one-to-many, etc.) can be tricky in Entity Framework Code First. This article provides sample code for doing so.

Self-Referencing

Scenario

A table references itself via a foreign key. A classic example of this is an Employee table where the ManagerId column has a foreign key against the EmployeeID (the primary key on the table).

Sample Code

This is established purely via the Fluent API.

public class Employee
{
  [Key, Required]
   public int Id { get; set; }   

   public int? ManagerId { get; set; }
 
   public Employee Manager { get; set; }
}

modelBuilder.Entity<Employee>()
                .HasOptional(r => r.Manager)
                .WithMany()
                .HasForeignKey(r => r.ManagerId)
                .WillCascadeOnDelete(false);