EntityFramework Prevent many to many cascade delete

352 views Asked by At

I have a cascade delete on a database and I don't want EF to do cascade delete for this many to many relationship, because it's redundant and slow.

    public class ArtikliBojeEC : EntityTypeConfiguration<ArtikliBoje>
{
    public ArtikliBojeEC()
    {
        this.HasMany(e => e.ArtikliVelicine).WithMany(e => e.ArtikliBoje)
            .Map(m => m.ToTable("ArtikliBojeVelicine").MapLeftKey("ArtikliBojeId").MapRightKey("ArtikliVelicineId"));
        this.Ignore(e => e.VezaNaVelicinu);
    }
}

I also tried putting this OnModelCreating, with no effect, EF still calls delete for every many to many link table:

            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
1

There are 1 answers

4
Dan Cao On

Have you tried this?

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
    relationship.DeleteBehavior = DeleteBehavior.Restrict;
}