Entity Framework Core - 两个实体之间的多个一对多关系 [英] Entity Framework Core - Multiple one-to-many relationships between two entities

查看:12
本文介绍了Entity Framework Core - 两个实体之间的多个一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有什么想法吗?

推荐答案

您必须告诉 Entity Framework 两个实体中的哪些属性涉及一个关联.在流畅的映射 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 不允许这样做,因为它臭名昭著的多级联路径"限制.其中一个key不能级联,只能通过fluent 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.

这篇关于Entity Framework Core - 两个实体之间的多个一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆