代码优先:如何映射这两个实体 [英] Code First: How to map these two entities

查看:70
本文介绍了代码优先:如何映射这两个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个实体,Team和Match。在每场比赛中,有两支球队,HomeTeam和AwayTeam。一支球队可以有很多比赛,但是HomeTeam和AwayTeam每人只能有一支球队。我只提供了每个课程的基础知识:

Let's say that I have two entities, Team and Match. In every Match, there are two teams, the HomeTeam and the AwayTeam. A Team can have many matches, but HomeTeam and AwayTeam can only have one team each. I have provided just the basics for each of the classes:

    公共课程团队

    public class Team

     {

    {

         public int TeamId {get;组; }

        public int TeamId { get; set; }

         public string Name {get;组; }

        public string Name { get; set; }

}

 

公共课比赛

{

         public int MatchId {get;组; }

        public int MatchId { get; set; }

         public int HomeTeamId {get;组; }

        public int HomeTeamId { get; set; }

         public int AwayTeamId {get;组; }

        public int AwayTeamId { get; set; }

}

如何映射?我尝试过(设置ICollection< Match>匹配并尝试映射它,但我得到HomeTeam和AwayTeam不能有相同的反向关系(类似的东西)。

How can I map this? I tried (with setting ICollection<Match> Matches and tried to map it, but I got that HomeTeam and AwayTeam can't have the same inverse relationship (something like that).

谢谢。

推荐答案

以下是完整的映射:


public class MyContext : DbContext
{
  public DbSet<Team> Teams { get; set; }
  public DbSet<Match> Matches { get; set; }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Match>()
      .HasRequired(m => m.HomeTeam)
      .WithMany(t => t.HomeMatches)
      .HasConstraint((m, t) => m.HomeTeamId == t.TeamId);

    modelBuilder.Entity<Match>()
      .HasRequired(m => m.AwayTeam)
      .WithMany(t => t.AwayMatches)
      .HasConstraint((m, t) => m.AwayTeamId == t.TeamId);
  }
}

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

  public ICollection<Match> AwayMatches { get; set; }
  public ICollection<Match> HomeMatches { get; set; }
}

public class Match
{
  public int MatchId { get; set; }
  public int HomeTeamId { get; set; }
  public int AwayTeamId { get; set; }

  public Team HomeTeam { get; set; }
  public Team AwayTeam { get; set; }
}


这篇关于代码优先:如何映射这两个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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