实体框架核心-两个实体之间的多个一对多关系

实体框架核心-两个实体之间的多个一对多关系

问题描述:

我有两个实体-团队游戏。一个团队可以有很多场比赛(一对多)。

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

所以看起来像这样:

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

        public ICollection<Game> Games { get; set; }
    }

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

        public int TeamId { get; set; }
        public Team Team { get; set; }
    }

这很好用,但我想通过将游戏分为两类-主场和客场游戏。但是,这将在两个实体之间引入另一种关系,我不确定如何定义它。

This works nice, but I want to make it a little more refined by splitting the games into two categories - Home and Away games. This will however introduce another relationship between the two entities and I'm not sure how to define it.

我想这会是这样吗?

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

        public ICollection<Game> HomeGames { get; set; }
        public ICollection<Game> AwayGames { get; set; }
    }

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

        public int HomeTeamId { get; set; }
        public Team HomeTeam { get; set; }

        public int AwayTeamId{ get; set; }
        public Team AwayTeam { get; set; }
    }

这样做会混淆实体框架,并且无法决定如何解决关系。

Doing this confuses Entity Framework and it can't decide how to settle the relationships.

有什么想法吗?

您必须告诉实体一个实体涉及两个实体中的哪些属性的框架。在流利的Mapping API中,这是:

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);
}

您必须使用fluent API,因为默认情况下,EF会尝试创建两个具有级联删除的外键。由于臭名昭著的多级联路径限制,SQL Server不允许这样做。密钥之一不应该是级联的,只能由流利的API配置。

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.