EF Core 2.2 - Two foreign keys to same table

不打扰是莪最后的温柔 提交于 2021-02-08 05:42:18

问题


I have a similar problem to the one posted here: Entity Framework Code First - two Foreign Keys from same table, however it's very old and doesn't apply to Core and I can't get the suggestions to work for me.

Basically, I'm trying to create a fixture table which will have two foreign keys to the team table. A fixture is made up of a home team and an away team. Having nullable fields isn't an option.

Consider a fixture, with two teams.

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>();
}

I get the error...

Unable to determine the relationship represented by navigation property 'Fixture.HomeTeam' of type 'Team'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

So I tried to add some OnModelCreating code in the database context:

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);
    }

Then I got the error:

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.

Can anyone help with getting this setup please?

Thanks.


回答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; }
}

This way navigation will work. Also as suggested by @Ivan remove duplicate getters and setters.



来源:https://stackoverflow.com/questions/54418186/ef-core-2-2-two-foreign-keys-to-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!