[英]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
: 我试图创建一个(在我看来)非常简单的设置,但是我不知道为什么在运行
Update-Database
时为什么总是出现此错误:
Introducing FOREIGN KEY constraint 'FK_dbo.Breweries_dbo.Pages_PageId' on table 'Breweries' may cause cycles or multiple cascade paths.
在表“ Breweries”上引入FOREIGN KEY约束“ FK_dbo.Breweries_dbo.Pages_PageId”可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
I am trying to setup this structure: 我正在尝试设置此结构:
Brewery
> Page
> IdentityUser
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. 我看过很多其他的Stack Overflow帖子,似乎我应该在
OnModelCreating
进行设置,但是我OnModelCreating
。 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. 我想,以避免一个
ICollection<Brewery> Breweries
的财产Page
,因为我想许多不同的实体参考Page
的实体,它是无关一个Page
是谁引用它。
I am new to Entity Framework and Code First so I might have approached this wrong without knowing. 我是Entity Framework和Code First的新手,所以我可能不知不觉地遇到了这个错误。 I would appreciate any help to setup the relationships correct.
我会很高兴对建立正确的关系有所帮助。
As the association between Page
and Brewery
is required, EF defaults to cascaded delete. 由于需要
Page
和Brewery
之间的关联,因此EF默认为级联删除。 But if there are many entities referring to Page
there will be multiple cascade paths and you have to override the default: 但是,如果有很多引用
Page
实体,则会有多个级联路径,您必须覆盖默认值:
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
. 同样,这将替换
Brewery.PageId
上的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.