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

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<Team>().HasMany(t => t.HomeGames)
        .WithOne(g => g.HomeTeam)
        .HasForeignKey(g => g.HomeTeamId);
    modelBuilder.Entity<Team>().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.


Base on Relationships - EF Core | Microsoft Docs you can use Data Annotations

Data Annotations

There are two data annotations that can be used to configure relationships, [ForeignKey] and [InverseProperty].

[ForeignKey]

You can use the Data Annotations to configure which property should be used as the foreign key property for a given relationship. This is typically done when the foreign key property is not discovered by convention.

[InverseProperty]

You can use the Data Annotations to configure how navigation properties on the dependent and principal entities pair up. This is typically done when there is more than one pair of navigation properties between two entity types.

public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty("HomeTeam")]
        public ICollection<Game> HomeGames { get; set; }

        [InverseProperty("AwayTeam")]
        public ICollection<Game> AwayGames { get; set; }
    }

public class Game
    {
        public int Id { get; set; }
        public DateTime Date { get; set; }

        public int HomeTeamId { get; set; }
        [ForeignKey("HomeTeamId")]
        public Team HomeTeam { get; set; }

        public int AwayTeamId{ get; set; }
        [ForeignKey("AwayTeamId")]
        public virtual Team AwayTeam { get; set; }
    }

if you use db.Database.Migrate() you will get erro

System.Data.SqlClient.SqlException: 'Introducing FOREIGN KEY constraint 'FK_Games_Teams_HomeTeamId' on table 'Games' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors

you can make HomeTeamId AwayTeamId int? nullable

public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty("HomeTeam")]
        public ICollection<Game> HomeGames { get; set; }

        [InverseProperty("AwayTeam")]
        public ICollection<Game> AwayGames { get; set; }
    }

public class Game
    {
        public int Id { get; set; }
        public DateTime Date { get; set; }

        public int? HomeTeamId { get; set; }
        [ForeignKey("HomeTeamId")]
        public Team HomeTeam { get; set; }

        public int? AwayTeamId{ get; set; }
        [ForeignKey("AwayTeamId")]
        public virtual Team AwayTeam { get; set; }
    }

or see Cascade Delete - EF Core | Microsoft Docs

  • here the full code i tested and working ( db first not code first )

  • for code first use int?

  • for Program.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using Microsoft.EntityFrameworkCore;
    
    namespace stackoverflow54196199
    {
    
    public class Team
    {
    
        public int Id { get; set; }
        public string Name { get; set; }
    
        [InverseProperty("HomeTeam")]
        public ICollection<Game> HomeGames { get; set; }
    
        [InverseProperty("AwayTeam")]
        public ICollection<Game> AwayGames { get; set; }
    }
    
    public class Game
    {
        public int Id { get; set; }
        public DateTime Date { get; set; }
    
        public int HomeTeamId { get; set; }
        [ForeignKey("HomeTeamId")]
        public Team HomeTeam { get; set; }
    
        public int AwayTeamId { get; set; }
        [ForeignKey("AwayTeamId")]
        public Team AwayTeam { get; set; }
    }
    
    
    public class MyContext : DbContext
    {
        public DbSet<Game> Games { get; set; }
        public DbSet<Team> Teams { get; set; }
    
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=.;Integrated Security=true;Initial Catalog=stackoverflow54196199;Persist Security Info=False;");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var db = new MyContext();
            foreach (var game in db.Games.Include(i => i.AwayTeam).Include(i => i.HomeTeam))
            {
                Console.WriteLine(game.HomeTeam.Name);
                Console.WriteLine(game.AwayTeam.Name);
    
            }
            Console.ReadLine();
        }
    }
    }
    
  • for stackoverflow54196199.csproj

    <PropertyGroup>
      <OutputType>Exe</OutputType>
      <TargetFramework>netcoreapp2.1</TargetFramework>
    </PropertyGroup>
    
    <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.1.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
     </ItemGroup>