Entity Framework Core - Multiple one-to-many relationships between two entities

前端 未结 2 1088
死守一世寂寞
死守一世寂寞 2020-12-20 14:58

I have two entities - Team and Game. A team can have many games (One-To-Many).

So that would look something like this:



        
2条回答
  •  时光说笑
    2020-12-20 15:47

    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.

提交回复
热议问题