I’m have the following Entity Framwork objects:
Evaluation, Stage, Apartment
Evaluation contains many Stages and Stage contains many Apartments.
I’m trying to deleted a certain stage as follows:
var deletedStages =
originalEvaluation.Stages.Where(s => s.State == StateTypes.Deleted);
deletedStages.ToList().ForEach(stage =>
{
stage.Apartments.ToList().ForEach(
apartment => stage.Apartments.Remove(apartment)
);
originalEvaluation.Stages.Remove(stage);
});
deletedStages.ToList().ForEach(stage =>
{
stage.Apartments.ToList().ForEach(apartment =>
shechtmanEntities.Apartments.DeleteObject(apartment)
);
shechtmanEntities.Stages.DeleteObject(stage);
});
}
}
try
{
shechtmanEntities.SaveChanges();
}
But I’m keep getting an Exception : “The relationship could not be changed because one or more of the foreign-key properties is non-nullable”.
I know it has to do with a null foreign-key, but I can’t understand which? and Why?
Thanks.
If you cannot Cascade Delete (SQL server can be funny about that: https://stackoverflow.com/a/6065583/613004) asdutzu suggests, then:
If it’s one-to-many relationship (sounds like it is), then you’ll need to manually delete each child object and save-changes before deleting the parent. I.E. delete the apartment (or re-assign it to another Stage), then delete the stage, and so on.
Otherwise, if it’s many-to-many, and the joining table is exposed through the entity model, delete the joins between the stages and apartments first, then delete the stage. If not, then
detachthe apartment from the stage and save changes before deleting the stage.