title: EntityFramework: How to configure Cascade-Delete to nullify Foreign Keys
body: <p>EntityFramework's documentation states that the following behavior is possible:</p>
  
  <blockquote>
    <p>If a foreign key on the dependent entity is nullable, Code First does
    not set cascade delete on the relationship, and when the principal is
    deleted the foreign key will be set to null.</p>
  </blockquote>
  
  <p>(from <a href="http://msdn.microsoft.com/en-us/jj591620">http://msdn.microsoft.com/en-us/jj591620</a>)</p>
  
  <p>However, I cannot achieve such a behavior.</p>
  
  <p>I have the following Entities defined with code-first:</p>
  
  <pre><code>public class TestMaster
  {
      public int Id { get; set; }
      public string Name { get; set; }        
      public virtual ICollection&lt;TestChild&gt; Children { get; set; }       
  }
  
  public class TestChild
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual TestMaster Master { get; set; }
      public int? MasterId { get; set; }
  }
  </code></pre>
  
  <p>Here is the Fluent API mapping configuration:</p>
  
  <pre><code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Entity&lt;TestMaster&gt;()
                      .HasMany(e =&gt; e.Children)
                      .WithOptional(p =&gt; p.Master).WillCascadeOnDelete(false);
  
          modelBuilder.Entity&lt;TestChild&gt;()
                      .HasOptional(e =&gt; e.Master)
                      .WithMany(e =&gt; e.Children)
                      .HasForeignKey(e =&gt; e.MasterId).WillCascadeOnDelete(false);
      }
  </code></pre>
  
  <p>Foreign Key is nullable, navigation property is mapped as Optional, so I expect the cascade delete to work as described as MSDN - i.e. to nullify MasterID's of all children and then delete the Master object.</p>
  
  <p>But when I actually try to delete, I get the FK violation error:</p>
  
  <pre><code> using (var dbContext = new TestContext())
          {
              var master = dbContext.Set&lt;TestMaster&gt;().Find(1);
              dbContext.Set&lt;TestMaster&gt;().Remove(master);
              dbContext.SaveChanges();
          }
  </code></pre>
  
  <p>On SaveChanges() it throws the following:</p>
  
  <pre><code>System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
  ----&gt; System.Data.UpdateException : An error occurred while updating the entries. See the inner exception for details.
  ----&gt; System.Data.SqlClient.SqlException : The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.TestChilds_dbo.TestMasters_MasterId". The conflict occurred in database "SCM_Test", table "dbo.TestChilds", column 'MasterId'.
  The statement has been terminated.
  </code></pre>
  
  <p>Am I doing something wrong or did I misunderstood what the MSDN says?</p>