Relationships in Entity Framework Code First


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.



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; }

                .HasOptional(r => r.Manager)
                .HasForeignKey(r => r.ManagerId)