【问题标题】:Entity Framework, having a navigation property connected to two (or more?) scalar properties实体框架,具有连接到两个(或更多?)标量属性的导航属性
【发布时间】:2014-03-04 19:36:32
【问题描述】:

实体框架有点问题,到处都找不到答案。

我正在尝试为排球队设置数据库/模型。

public class Match
{
    public int ID { get; set; }
    public DateTime GameTime { get; set; }
    public virtual Team HTeam { get; set; }
    public virtual Team ATeam { get; set; }
    public String HScore { get; set; }
    public String AScore { get; set; }
}
public class Team
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual List<Match> Matches { get; set; }
}

一个球队可以是客队或主队,所以对于 Team.Matches,我希望它是球队所在的列表。这可以用实体框架来完成吗? 当我像上面那样做时,Match 中有一个新列存储 team_id,但它是空白的。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    我不知道有什么方法可以让Team.Matches 根据两种可能的关系进行填充。

    从数据库的角度考虑的另一种方式是,您的 Match 表与 Team 具有多对多关系,您只是将 Match 限制为只有 2 个 Team,其中一个是主队。

    考虑以下几点:

    public class Match
    {
      public int ID { get; set; }
      public DateTime GameTime { get; set; }
      public virtual List<MatchTeam> MatchTeams { get; set; }
    }
    
    public class MatchTeam
    {
      public virtual Match Match { get; set; }
      public virtual Team Team { get; set; }
      public bool IsHomeTeam { get; set; }
      public string Score { get; set; }
    }
    
    public class Team
    {
      public int ID { get; set; }
      public string Name { get; set; }
      public virtual List<MatchTeam> MatchTeams { get; set; }
    }
    

    在参考比赛/球队之前,会有一个中间步骤来获取比赛/球队信息(IsHomeTeam、Score)。

    string homeTeamScore = string.Format("Team {0} scored {1}",
      match.MatchTeams.First(mt => mt.IsHomeTeam).Team.Name,
      match.MatchTeams.First(mt => mt.IsHomeTeam).Score
    );
    

    您可以添加一个 HomeTeam 属性并告诉 EF 忽略它,如下所示:

    public Team HomeTeam
    {
      get
      {
        return MatchTeams.FirstOrDefault(mt => mt.IsHomeTeam);
      }
    }
    

    我会把set留给你玩,如果你卡住了,请告诉我。

    【讨论】:

    • 这有点超出我的理解。我最终使用了一个包含团队和匹配数组的视图模型,在代码中获取匹配的团队以及 team.id 与主队或客队匹配的匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多