EntityFramework防止多对多级联删除

时间:2017-11-20 01:47:39

标签: c# entity-framework many-to-many

我在数据库上进行级联删除,并且我不希望EF为这种多对多关系进行级联删除,因为它冗余而且速度慢。

    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);
    }
}

我也尝试过这个OnModelCreating,没有任何效果,EF仍然会为每个多对多链接表调用delete:

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

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

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