简体   繁体   中英

Two foreign keys to the same table in EF Core

I am creating a SQL Database using entity framework and fluent API. Basically a game has 2 players and only the Player1 will be assigned in the creation of the game. So far I've created the following code:

public class Game
{
    public int ContextId { get; set; }
    public DateTime DateStart { get; set; }
    public DateTime? DateEnd { get; set; }

    public virtual Player Player1 { get; set; }
    public virtual Player Player2 { get; set; }
}

public class Player
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual IList<Game>  Games { get; set; }
}


public void Configure(EntityTypeBuilder<Game> gameConfiguration)
{
    gameConfiguration.ToTable("games", GameDbContext.DEFAULT_SCHEMA);
    gameConfiguration.HasKey(c => c.ContextId).Metadata.AddAnnotation("DatabaseGenerated", DatabaseGeneratedOption.None);
    gameConfiguration.Property(c => c.ContextId).ValueGeneratedNever();
    gameConfiguration.Property(c => c.DateStart).IsRequired();
    gameConfiguration.Property(c => c.DateEnd).IsRequired(false);

    gameConfiguration.HasOne(c => c.Player1).WithMany(g => g.Games).HasForeignKey("ForeignKey_Game_Player1");
    gameConfiguration.HasOne(c => c.Player2).WithMany(g => g.Games).HasForeignKey("ForeignKey_Game_Player2");
}

I am getting an exception when launching the app.

InvalidOperationException: Cannot create a relationship between 'Player.Games' and 'Game.Player2', because there already is a relationship between 'Player.Games' and 'Game.Player1'. Navigation properties can only participate in a single relationship.

How can I achieve it?

You can define your relations like below.

public virtual IList<Game>  CreatedGames { get; set; }
public virtual IList<Game>  ParticipatedGames { get; set; }

And configure them as follows.

gameConfiguration.HasOne(c => c.Player1).WithMany(g => g.CreatedGames).HasForeignKey("ForeignKey_Game_Player1");
gameConfiguration.HasOne(c => c.Player2).WithMany(g => g.ParticipatedGames).HasForeignKey("ForeignKey_Game_Player2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM