I have an optional relationship from a Child to a Parent class. I would like to get an exception on SubmitChanges when the parent object is marked for deletion if there are still children around that reference it.
The configuration I’ve tried is this (there is no navigation property from the parent to the children):
modelBuilder.Entity<Child>()
.HasOptional<Parent>(child => child.Parent)
.WithMany()
.HasForeignKey(child => child.ParentId)
.WillCascadeOnDelete(false);
Like this EF sets the children’s ParentId property to null when deleting the parent, which is not what I want.
It works if the relationship is configured as required:
modelBuilder.Entity<Child>()
.HasRequired<Parent>(child => child.Parent)
.WithMany()
.HasForeignKey(child => child.ParentId)
.WillCascadeOnDelete(false);
This throws an exception, which would be the desired behaviour. But the relationship has to be optional. Is this possible with EF 4.3.1 using Code First?
No. That is the difference between optional and required. Required = must have a principal record and if you delete the principal record without cascading you will get an exception. Optional = doesn’t need a principal record and if you delete the principal record without cascading the FK is set to null.
If you need anything else you must handle it yourselves.