EF4.1 Code First: How to stop delete cascade for a relationship in a dependent object without a navigation property

c# cascading-deletes ef-code-first entity-framework foreign-keys


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:

    .HasRequired(c => c.parent)
    .WithMany(p => p.Childrens)

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.

9/3/2017 11:40:44 AM

Accepted Answer

You must configure it from the other side of the association:

    .HasMany(p => p.Children)
    .HasForeignKey(c => c.ParentEntityId)
2/3/2012 11:06:13 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow