【问题标题】:How to create a model with self reference in Entity Framework Code-First?如何在实体框架代码优先中创建具有自引用的模型?
【发布时间】:2020-02-02 01:15:19
【问题描述】:

我正在使用 Entity Framework Core 3.1 并尝试处理简单的场景:在体育联赛中有很多比赛,但我想处理推迟的比赛。这是我的模型:

public class Game
{
    public int GameId { get; set; }
    public DateTime StartTime { get; set; }
    public int HomeTeamId { get; set; }
    public int AwayTeamId { get; set; }
    public int? PostponedGameId { get; set; } // Original game that didn't happened and was postponed to 'this' game. 

    public Team HomeTeam { get; set; }
    public Team AwayTeam { get; set; }
    public Game PostponedGame { get; set; }
}

显然对于大多数游戏PostponedGameId 将为空。

如何创建一个fluent API 来生成可为空的 FK (PostponedGameId)?

编辑:

这是我目前所拥有的:

        modelBuilder.Entity<Game>()
            .HasOne<Game>(g => g.PostponedGame)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade);

但我不知道如何声明 PostponedGameId 是外键。我什至不确定这是否正确,因为我没有在没有指定外键的情况下运行它。

【问题讨论】:

  • this 对您有帮助吗?
  • @Twenty 不完全是。在这篇文章中有自我参考,但“一对多”。我需要“一对一”的自我参考。
  • 我说的是.IsRequired()方法。
  • @Twenty 我不明白。这不是必需的。大多数比赛没有延期
  • IsRequired 方法采用布尔参数,该参数定义是否需要 FK。

标签: c# .net-core ef-code-first entity-framework-migrations ef-core-3.0


【解决方案1】:

所以我建议如下:

modelBuilder.Entity<Game>()
            .HasOne<Game>(g => g.PostponedGame)
            .WithOne()
            .HasForeignKey<Game>(g => g.PostponedGameId) // Defines the FK 
            .OnDelete(DeleteBehavior.Cascade)
            .IsRequired(false); // Tells ef-core that the FK is optional

我目前无法验证代码,但它应该可以工作。

【讨论】:

    猜你喜欢
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2013-12-05
    • 2021-09-01
    相关资源
    最近更新 更多