EF Core 2.2-指向同一表的两个外键

时间:2019-01-29 09:50:06

标签: asp.net-mvc foreign-keys entity-framework-core

我有一个与此处发布的问题类似的问题: Entity Framework Code First - two Foreign Keys from same table,但是它已经很老了,不适用于Core,我也无法获得适合我的建议。

基本上,我正在尝试创建一个夹具表,该表将具有两个到团队表的外键。固定装置由主队和客队组成。不能设置可为空的字段。

考虑一个有两个团队的固定装置。

public class Fixture
{
    public int Id { get; set; }
    public Team HomeTeam { get; set; }
    public int HomeTeamId { get; set; }
    public Team AwayTeam { get; set; }
    public int AwayTeamId { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team AwayTeam { get; set; }
}



public class Team
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public String Name { get; set; }
    public ICollection<Fixture> HomeFixtures { get; set; } = new List<Fixture>();
    public ICollection<Fixture> AwayFixtures { get; set; } = new List<Fixture>();
}

我得到了错误...

无法确定类型为“团队”的导航属性“ Fixture.HomeTeam”所表示的关系。要么手动配置关系,要么使用“ [NotMapped]”属性或“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”忽略此属性。

所以我试图在数据库上下文中添加一些OnModelCreating代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Fixture>()
                    .HasOne(m => m.HomeTeam)
                    .WithMany(t => t.HomeFixtures)
                    .HasForeignKey(m => m.HomeTeamId)
                    .OnDelete(DeleteBehavior.Restrict);


        modelBuilder.Entity<Fixture>()
                    .HasOne(m => m.AwayTeam)
                    .WithMany(t => t.AwayFixtures)
                    .HasForeignKey(m => m.AwayTeamId)
                    .OnDelete(DeleteBehavior.Restrict);
    }

然后我得到了错误:

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

有人可以帮助您进行此设置吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

public class Fixture
{
    public int Id { get; set; }
    public int HomeTeamId { get; set; }
    public int AwayTeamId { get; set; }

    [ForeignKey("HomeTeamId")]
    public virtual Team HomeTeam { get; set; }

    [ForeignKey("AwayTeamId")]
    public virtual Team AwayTeam { get; set; }
}

通过这种方式导航将起作用。还应@Ivan的建议,删除重复的getter和setter。