title: Fix 'The DELETE statement conflicted with the REFERENCE constraint' error with code
body: <p>I have an Asp.Net MVC 5 website with EntityFramework Code First. In my site, I have a <code>Restaurant</code> model with the following code:</p>
  
  <pre><code>public class Restaurant
  {
      [Required]
      public string Name { get; set; }
  
      //....
      public virtual IList&lt;RestaurantType&gt; Types { get; set; }
  }
  </code></pre>
  
  <p>And the code for the <code>RestaurantType</code> is:</p>
  
  <pre><code>public class RestaurantType
  {
      [Key]
      public int ID { get; set; }
  
      [Required]
      public string Type { get; set; }
  
      public virtual Restaurant Restaurant { get; set; }
  }
  </code></pre>
  
  <p>When I try to delete the <code>restaurant</code> from context, I get the following error:</p>
  
  <p><code>The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.RestaurantTypes_dbo.Restaurants_Restaurant_ID". The conflict occurred in database "aspnet-Test-20131111052251", table "dbo.RestaurantTypes", column 'Restaurant_ID'.
  The statement has been terminated.</code></p>
  
  <p>I have data in production and I want to handle this as silently as possible. I tried the following code:</p>
  
  <pre><code>            for (int i = 0; i &lt; restaurant.Types.Count; i++)
              {
                  var type = restaurant.Types[i];
                  db.RestaurantTypes.Remove(type);
                  restaurant.Types.Remove(type);
              }
  
              db.Restaurants.Remove(restaurant);
              await db.SaveChangesAsync();
  </code></pre>
  
  <p>But I get the same error. I checked the database and there's no row with the restaurant ID. I even tried this:</p>
  
  <pre><code>        var list = db.RestaurantTypes.Where(t =&gt; t.Restaurant == null || t.Restaurant.ID == restaurant.ID);
          foreach (var ib in list)
          {
              db.RestaurantTypes.Remove(ib);
          }
          db.SaveChanges();
  </code></pre>
  
  <p>It didn't work either. Is there a way for me to fix this with C# code?</p>