Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

前端 未结 18 964
天涯浪人
天涯浪人 2020-11-22 02:37

I\'ve been wrestling with this for a while and can\'t quite figure out what\'s happening. I have a Card entity which contains Sides (usually 2) - and both Cards and Sides h

18条回答
  •  旧时难觅i
    2020-11-22 03:11

    Because Stage is required, all one-to-many relationships where Stage is involved will have cascading delete enabled by default. It means, if you delete a Stage entity

    • the delete will cascade directly to Side
    • the delete will cascade directly to Card and because Card and Side have a required one-to-many relationship with cascading delete enabled by default again it will then cascade from Card to Side

    So, you have two cascading delete paths from Stage to Side - which causes the exception.

    You must either make the Stage optional in at least one of the entities (i.e. remove the [Required] attribute from the Stage properties) or disable cascading delete with Fluent API (not possible with data annotations):

    modelBuilder.Entity()
        .HasRequired(c => c.Stage)
        .WithMany()
        .WillCascadeOnDelete(false);
    
    modelBuilder.Entity()
        .HasRequired(s => s.Stage)
        .WithMany()
        .WillCascadeOnDelete(false);
    

提交回复
热议问题