Let's say I have these two very basic entities:
public class ParentEntity
{
public int Id;
public virtual ICollection<ChildEntity> Childrens;
}
public class ChildEntity
{
public int Id;
public int ParentEntityId; // Foreign Key
public virtual ParentEntity parent; // [NOTWANTED]
}
For some reasons, I don't want the ChildEntity to hold a reference back to his parent. I just want it to keep the ParentEntity id but nothing more. Up until now, no problem, I just delete the [NOTWANTED] line, and everything works as expected.
My problem here is: how to disable the cascade delete in that specific case?
If I still had the parent navigation property it would be as easy as:
modelBuilder.Entity<ChildEntity>()
.HasRequired(c => c.parent)
.WithMany(p => p.Childrens)
.WillCascadeOndelete(false)
However without the navigation property I have no idea how I can achieve to disable the cascade on delete (without disabling it globally of course, nor per table, but just for the relation).
What I have done right now is to set the foreign key as a nullable int, in order to disable the cascade on delete, but that's not pretty:
public int? ParentEntityId; // Foreign Key - nullable just to disable cascade on delete
How can I get it to work with fluent API? Think it should be possible.
You must configure it from the other side of the association:
modelBuilder.Entity<ParentEntity>()
.HasMany(p => p.Children)
.WithRequired()
.HasForeignKey(c => c.ParentEntityId)
.WillCascadeOnDelete(false);