title: Deleting an Entity Framework object that may or may not already exist in the database
body: <p>I'm using the Entity Framework 6, database first (I'm new to EF). I have two entity classes, <code>Structure</code> and <code>Contour</code>, where a <code>Structure</code> may contain multiple objects of type <code>Contour</code>. I would like to be able to remove <code>Contours</code> whether or not they already exist in the database. For example, if I add a new <code>Contour</code> to an existing <code>Structure</code> object like this:</p>
  
  <pre><code>Contour contour = new Contour
  {
      Structure = structure,
  };
  </code></pre>
  
  <p>I can delete it like this:</p>
  
  <pre><code>contour.Structure = null;
  </code></pre>
  
  <p>But if the contour already exists in the database and I delete it, saving the entity context throws the exception "The relationship could not be changed because one or more of the foreign-key properties is non-nullable..."</p>
  
  <p>That exception tells me that the entity context wasn't aware that it's supposed to delete that <code>Contour</code>. My fix was to delete a <code>Contour</code> as follows:</p>
  
  <pre><code>contour.Structure = null;
  EntityContext.Contours.Remove(contour);
  </code></pre>
  
  <p>But if the contour doesn't exist in the database already (because it was just added), then the entity context is not aware of it and it doesn't find it in its <code>Contours</code> list. So then I modified my delete method to this:</p>
  
  <pre><code>contour.Structure = null;
  if (EntityContext.Contours.Local.Contains(contour))
  {
      EntityContext.Contours.Remove(contour);
  }
  </code></pre>
  
  <p>This appears to work so far, but is this how I'm supposed to delete entity objects that may or may not already exist in the database?</p>