【发布时间】: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