gpt4 book ai didi

entity-framework - EF6 Code First - 可能导致循环或多个级联路径

转载 作者:行者123 更新时间:2023-12-04 11:24:56 24 4
gpt4 key购买 nike

我首先使用 EF6 代码。
我有两个类(class):

public class Player
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }

[Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")]
public string Name { get; set; }

[Required]
public int TeamClubId { get; set; }

[Required]
public int TeamNationalId { get; set; }

[Required, ForeignKey("TeamClubId")]
public virtual Team Club { get; set; }

[Required, ForeignKey("TeamNationalId")]
public virtual Team National { get; set; }

}

和:
 public class Team
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
public string Name { get; set; }

[Required]
public TeamType Type { get; set; }

public virtual ICollection<Player> Players { get; set; }
}

这是我的两个类与他们的关系。
一名球员属于两支球队:俱乐部和国家队。
一支球队可以是俱乐部的,也可以是国家队的,并且拥有一批球员。

在我的上下文文件中,我使用:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Player>()
.HasRequired<Team>(p => p.National)
.WithMany(t => t.Players)
.WillCascadeOnDelete(false);

base.OnModelCreating(modelBuilder);
}

运行迁移工具更新数据库时,出现以下错误:

在表 'Players' 上引入 FOREIGN KEY 约束 'FK_dbo.Players_dbo.Teams_TeamNationalId' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
无法创建约束。请参阅以前的错误。

我该如何解决?

最佳答案

使用 Fluent API:

        //player - national team relations
modelBuilder.Entity<Player>()
.HasRequired<Team>(p => p.National)
.WithMany()
.WillCascadeOnDelete(false);

//player - club team relations
modelBuilder.Entity<Player>()
.HasRequired<Team>(p => p.Club)
.WithMany()
.WillCascadeOnDelete(false);

关于entity-framework - EF6 Code First - 可能导致循环或多个级联路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com