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

时间:2019-06-24 21:04:29

标签: c# entity-framework-core

我正在使用实体框架和流畅的API创建一个SQL数据库。基本上,一个游戏有2位玩家,并且在创建游戏时只会分配Player1。 到目前为止,我已经创建了以下代码:

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

启动应用程序时出现异常。

  

InvalidOperationException:无法在之间创建关系   “ Player.Games”和“ Game.Player2”,因为已经有一个   “ Player.Games”和“ Game.Player1”之间的关系。导航   属性只能参与单个关系。

我该如何实现?

1 个答案:

答案 0 :(得分:0)

您可以如下定义关系。

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

并按如下所示配置它们。

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