I have two entities - Team and Game. A team can have many games (One-To-Many).
So that would look something like this:
You have to tell Entity Framework which properties in both entities are involved in one association. In fluent mapping API this is:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().HasMany(t => t.HomeGames)
.WithOne(g => g.HomeTeam)
.HasForeignKey(g => g.HomeTeamId);
modelBuilder.Entity().HasMany(t => t.AwayGames)
.WithOne(g => g.AwayTeam)
.HasForeignKey(g => g.AwayTeamId).OnDelete(DeleteBehavior.Restrict);
}
You have to use the fluent API because by default, EF will try to create two foreign keys with cascaded delete. SQL Server won't allow that because of its infamous "multiple cascade paths" restriction. One of the keys shouldn't be cascading, which can only be configured by the fluent API.