EF7 RC1 : Disable Cascade Delete

流过昼夜 提交于 2019-11-30 13:41:24

问题


In the RC1 of EntityFramework 7, released yesterday, Cascade Delete was added.

To disable it per relationship, I can use :

      builder.Entity<Site>().HasOne(e => e.Person)
      .WithMany(x => x.Sites).Metadata.DeleteBehavior = DeleteBehavior.Restrict;

I want to disable it globally for a DbContext, but I didn't find a way. How can I do ?


回答1:


Someone stated on the github project forum that the only way to do it right now is to iterate through all relationships in the method OnModelCreating(ModelBuilder builder), and set the DeleteBehavior property to DeleteBehavior.Restrict :

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



回答2:


Right now conventions are not configurable. The current CascadeDelete convention only applies to required relationships. Relationships Conventions: Cascade Delete on efproject.net (Official EF7 docs) You could disable the required relationship explicitly if you understand well the consequences.

        modelBuilder.Entity<Site>()
            .HasOne(p => p.Person)
            .WithMany(b => b.Sites)
            .IsRequired(false);

Otherwise (and recommended), you need to set the On Delete behavior explicitly ( as you already discovered).

        modelBuilder.Entity<Site>()
            .HasOne(p => p.Person)
            .WithMany(b => b.Sites)
            .OnDelete(DeleteBehavior.Restrict);



回答3:


If you don’t use Required on a property in model class, it’s generated as DeleteBehavior.Restrict by default. Use Required if you want to use DeleteBehavior.Cascade. You can see this by generating dummy migrations by using with/without Required.



来源:https://stackoverflow.com/questions/33807879/ef7-rc1-disable-cascade-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!