简体   繁体   中英

Foreign key may cause cycles or multiple cascade paths

I am trying to create a (in my opinion) quite simple setup, but I can't figure out why I keep getting this error when I run Update-Database :

Introducing FOREIGN KEY constraint 'FK_dbo.Breweries_dbo.Pages_PageId' on table 'Breweries' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

I am trying to setup this structure:

Brewery > Page > IdentityUser

This is my classes:

public class Brewery
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid BreweryId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [ForeignKey("Page")]
    public Guid PageId { get; set; }

    public virtual Page Page { get; set; }

    public virtual ICollection<Image> Images { get; set; }
}

public class Page
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid PageId { get; set;}
    [Required]
    public string Title { get; set; }

    public string Content { get; set; }
    [Required]
    [ForeignKey("CreatorUser")]
    public string CreatorUserId { get; set; }

    public virtual IdentityUser CreatorUser { get; set; }
}

I have seen a lot of other Stack Overflow posts and it seems like I should be setting something up in the OnModelCreating , but I can't get it right. I would like to avoid having a ICollection<Brewery> Breweries property on the Page , since I want many different entities to reference to the Page entity and it is irrelevant for a Page who is referencing to it.

I am new to Entity Framework and Code First so I might have approached this wrong without knowing. I would appreciate any help to setup the relationships correct.

As the association between Page and Brewery is required, EF defaults to cascaded delete. But if there are many entities referring to Page there will be multiple cascade paths and you have to override the default:

modelBuilder.Entity<Brewery>()
            .HasRequired(b => b.Page)
            .WithMany() // <= no inverse collection in Page.
            .HasForeignKey(b => b.PageId)
            .WillCascadeOnDelete(false);

You can only do this by fluent mapping. Also, this replaces the attributes on Brewery.PageId .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM