title: Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship
body: <p>Following the "Code First Modeling" section of the <a href="http://pluralsight.com/training/Courses/TableOfContents/entity-framework5-getting-started" rel="noreferrer">Pluralsight "Getting Started with Entity Framework 5" course by Julie Lerman</a>, I created two POCO classes with a <strong>one-to-zero-or-one</strong> relationship: a parent (User) and an <strong>optional</strong> child (UserDetail).</p>
  
  <p><a href="https://i.imgur.com/9wLj4Kj.png" rel="noreferrer">User and UserDetail data model diagram (click to view).</a></p>
  
  <p>Notice in the diagram that <strong>the UserId property is a primary key and a foreign key for UserDetail</strong>.</p>
  
  <p>Relevant code:</p>
  
  <pre><code>public class User
  {
      //...
  
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int UserId { get; set; }
  
      /* Has a 1:0..1 relationship with UserDetail */
      public virtual UserDetail UserDetail { get; set; }
  
      //...
  }
  
  public class UserDetail
  {
      //...
  
      /* Has a 0..1:1 relationship with User */
      public virtual User User { get; set; }
  
      [Key, ForeignKey("User")]
      public int UserId { get; set; }
  
      //...
  }
  
  public class EFDbContext : DbContext
  {
      public DbSet&lt;User&gt; Users { get; set; }
      //public DbSet&lt;UserDetail&gt; UserDetails { get; set; }  /* Explicit declaration not necessary. Context is aware of UserDetail entity due to 0..1:1 relationship with User */
  
      public EFDbContext()
      {
          Configuration.ProxyCreationEnabled = true;
          Configuration.LazyLoadingEnabled = true;
      }
  }
  
  public class UserRepository : IUserRepository
  {
      private EFDbContext _context = new EFDbContext();
  
      public void Delete(User entity)
      {
          entity = _context.Users.Find(entity.UserId);
  
          //...
  
          _context.Users.Remove(entity);
          _context.SaveChanges();
  
          //...
      }
  }
  </code></pre>
  
  <p>When the Delete() method in the UserRepository class is called, it does not delete the User record in the database because the foreign key in UserDetail does not have cascade delete enabled.</p>
  
  <blockquote>
    <p>The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.UserDetail_dbo.User_UserId".</p>
  </blockquote>
  
  <p>How would you enable cascading deletes for <strong>one-to-zero-or-one relationships</strong> using Entity Framework Code First (so that deleting a User automatically deletes UserDetail)?</p>