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


Consider that I have these two extremely fundamental 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]

I don't want the ChildEntity to keep a reference to his parent because of many factors. I just want the ParentEntity id to be retained; nothing else. As of right now, there is no issue; I just remove the [NOTWANTED] line, and everything functions as it should.

How can I deactivate the cascading delete in this particular situation?

It would be simple if I still had the parent navigation property to:

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

But I'm not sure how I can deactivate the cascade on deletion without the navigation property (without disabling it globally of course, nor per table, but just for the relation).

In order to avoid the cascade on deletion, all I've done so far is set the foreign key as a nullable int, but that's not ideal:

public int? ParentEntityId; // Foreign Key - nullable just to disable cascade on delete

How can I get it to work with fluent API? I believe it ought to be doable.

9/3/2017 11:40:44 AM

Accepted Answer

It must be set up from the association's opposite side:

    .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