我正在开发一个示例应用程序,人们可以在这里投注体育赛事并获得积分。它具有以下实体框架代码优先模型:
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; }
}
一个人可以为一场比赛下注,他可以下注任何其他人(竞争对手)。
模型将产生以下错误:
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.
我尝试删除OneToManyCascadeDeleteConvention
,添加流畅的配置以防止RaceBet的级联删除以及api的所有其他变体,但一切都失败了。
modelBuilder
.Entity<RaceBet>()
.HasRequired(x => x.Person)
.WithMany()
.HasForeignKey(x => x.PersonId)
.WillCascadeOnDelete(false);
我该如何解决这个问题?我的模型背后的概念是错误的吗?
谢谢!
答案 0 :(得分:0)
感谢Oleg的评论:
我无法使用以下代码重现异常:protected override void OnModelCreating(DbModelBuilder modelBuilder){ modelBuilder.Conventions.Add(新 System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConventi上()); modelBuilder .Entity()。HasRequired(x =&gt; x.Person) .WithMany()。HasForeignKey(x =&gt; x.PersonId) .WillCascadeOnDelete(假); }
这修复了模型的创建。