Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 815
darkey Avatar asked Feb 03 '12 22:02

darkey


People also ask

How do I remove a one to many relationship in Entity Framework?

after manual set the property,single call to "dbContext. As. Remove(someA)" work as expected!

How do I enable cascade delete in Entity Framework?

Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

What is disable on delete cascade in Oracle?

Anyway, you can disable the constraint by using: alter table TABLE_NAME disable constraint FK_CONSTRAINT_NAME; ( use 'enable' to re-enable it ).


1 Answers

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);
like image 179
Slauma Avatar answered Oct 17 '22 01:10

Slauma