title: Disable cascade delete with EF?
body: <p>I have 2 entities linked by a one-to-many relationship as follows (I used code first):</p>
  
  <pre><code>public class Computer
  {
      [Key]
      public int ComputerId { get; set; }
  
      [Required]
      public int ComputerIdInventory { get; set; }
  
      [DataType(DataType.Date)]
      public DateTime? AcquisitionDate { get; set; }
  
      [DataType(DataType.Date)]
      public DateTime? LastUpdate { get; set; }
  
      public string Comment { get; set; }
  
      //Foreign keys
      public int? ComputerModelId { get; set; }
  
      public int? EmployeeId { get; set; }
  
      //Navigation properties
      public virtual ICollection&lt;Screen&gt; Screens { get; set; }
  }
  
  public class Screen
  {
      [Key]
      public int ScreenId { get; set; }
  
      [Required]
      public int ScreenIdInventory { get; set; }
  
      public string Comment { get; set; }
  
      //Foreign keys
      public int? ComputerId { get; set; }
  
      //Navigation properties
      public virtual Computer Computer { get; set; }
  }
  </code></pre>
  
  <p>When I delete a computer that is linked to one or many screens, I have the following error: </p>
  
  <blockquote>
    <p>[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.</p>
  </blockquote>
  
  <p>I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :</p>
  
  <pre><code>modelBuilder.Conventions.Remove&lt;OneToManyCascadeDeleteConvention&gt;();
  modelBuilder.Conventions.Remove&lt;ManyToManyCascadeDeleteConvention&gt;();
  </code></pre>
  
  <p>And I tried this too: </p>
  
  <pre><code>modelBuilder.Entity&lt;Computer&gt;()
              .HasMany&lt;Screen&gt;(c =&gt; c.Screens)
              .WithOptional(s =&gt; s.Computer)
              .WillCascadeOnDelete(false);
  </code></pre>
  
  <p>But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account? </p>
  
  <p>Thank a lot !</p>
  
  <p>Edit: 
  Here is the delete code</p>
  
  <pre><code>public ActionResult DeleteConfirmed(int id)
      {
          Computer computer = db.Computers.Find(id);
          db.Computers.Remove(computer);
          db.SaveChanges();
          return RedirectToAction("Index");
      }
  </code></pre>