[英]EF FOREIGN KEY constraint may cause cycles or multiple cascade paths
I am developing a sample application where people can place bets on sports events and earn points. 我正在开发一个示例应用程序,人们可以在体育赛事上下注并赚取积分。 It has the following Entity Framework Code-First models: 它具有以下Entity Framework Code-First模型:
public class Person
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class Race
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class RaceBet
{
[Key]
public int Id { get; set; }
[Required]
public int RaceId { get; set; }
[Required]
public int PersonId { get; set; }
[Required]
public int CompetitorId { get; set; }
public virtual Race Race { get; set; }
public virtual Person Person { get; set; }
public virtual Person Competitor { get; set; }
}
A Person can place a bet for a Race and he can bet on any other Person (Competitor). 一个人可以为一场比赛下注,也可以对任何其他人(竞争对手)下注。
The models will produce the following error: 这些模型将产生以下错误:
Introducing FOREIGN KEY constraint 'FK_dbo.RaceBets_dbo.People_PersonId' on table 'RaceBets' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.
I tried removing the OneToManyCascadeDeleteConvention
, adding fluent configurations to prevent cascade delete for RaceBet and all other variations of the api, but everything fails. 我尝试删除OneToManyCascadeDeleteConvention
,添加流畅的配置以防止对RaceBet和所有其他版本的api进行级联删除,但是一切都会失败。
modelBuilder
.Entity<RaceBet>()
.HasRequired(x => x.Person)
.WithMany()
.HasForeignKey(x => x.PersonId)
.WillCascadeOnDelete(false);
How can I resolve this? 我该如何解决? Is the concept behind my models wrong? 我的模型背后的概念是否错误?
Thanks! 谢谢!
Thanks to Oleg for his comment: 感谢Oleg的评论:
I can't to reproduce exception with this code: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add(new System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConvention()); 我无法使用此代码重现异常:保护重写void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.Conventions.Add(new System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConvention()); modelBuilder .Entity() .HasRequired(x => x.Person) .WithMany() .HasForeignKey(x => x.PersonId) .WillCascadeOnDelete(false); modelBuilder .Entity().HasRequired(x => x.Person).WithMany().HasForeignKey(x => x.PersonId).WillCascadeOnDelete(false); } }
This fixed the model creation. 这修复了模型创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.