I'm using the Entity Framework 6, database first (I'm new to EF). I have two entity classes, Structure and Contour, where a Structure may contain multiple objects of type Contour. I would like to be able to remove Contours whether or not they already exist in the database. For example, if I add a new Contour to an existing Structure object like this:
Contour contour = new Contour
{
Structure = structure,
};
I can delete it like this:
contour.Structure = null;
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..."
That exception tells me that the entity context wasn't aware that it's supposed to delete that Contour. My fix was to delete a Contour as follows:
contour.Structure = null;
EntityContext.Contours.Remove(contour);
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 Contours list. So then I modified my delete method to this:
contour.Structure = null;
if (EntityContext.Contours.Local.Contains(contour))
{
EntityContext.Contours.Remove(contour);
}
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?