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.
after manual set the property,single call to "dbContext. As. Remove(someA)" work as expected!
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.
Anyway, you can disable the constraint by using: alter table TABLE_NAME disable constraint FK_CONSTRAINT_NAME; ( use 'enable' to re-enable it ).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With