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

Relationships in Entity Framework Code First

RSS
Modified on Thu, Jul 27, 2017, 8:01 AM by Administrator Categorized as 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);

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