【问题标题】:Entity Framework Self-Referencing Entity实体框架自引用实体
【发布时间】:2017-10-05 09:28:15
【问题描述】:

我正在建立一个数据库来存储双败淘汰赛的括号。锦标赛中的每场比赛都有两支球队互相比赛。在比赛的第一轮中,球队是根据种子确定的。在随后的回合中,球队是之前比赛的赢家和输家。

public class Match
{
    public int MatchId { get; set; }
    [Required]
    public virtual Round Round { get; set; }
    // other stuff to keep track of match results
    public virtual Team Team1 { get; set; }
    public virtual Team Team2 { get; set; }       
    [Required]
    public TeamSourceType SourceType1 { get; set; }
    [Required]
    public TeamSourceType SourceType2 { get; set; }
    public virtual Match SourceMatch1 { get; set; }
    public virtual Match SourceMatch2 { get; set; }
}

对于两个团队中的每一个,都有一个 TeamSourceType,它指示团队是如何确定的。如果 TeamSourceType1/2 指定了上一场比赛的赢家或输家,我需要 SourceMatch1/2 来引用从中获得赢家/输家的比赛。我正在使用 Entity Framework 6 Code First。我尝试了几种注释和流畅映射的组合,但没有任何效果。 我得到“多重性无效......”和“多重性约束被违反......”。

我需要哪些注释和/或流畅的映射来完成这项工作?

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

我不得不在我的一个项目中使用自引用表,下面的方法对我有用。 在我的实体类中,我这样定义了FK

public int? RelatedMatchId{ get; set; }
public virtual Match SourceMatch1 { get; set; }

然后,我将此规范添加到modelbuilder 中的OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Match>()
        .HasOptional(c => c.SourceMatch1 )
        .WithMany()
        .HasForeignKey(c => c.RelatedMatchId);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2017-07-22
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多