2017-10-20 180 views
0

我正在尝试执行代码优先迁移,但是当我迁移时,其中一个模型/表的行为非常奇怪。实体框架6代码优先关系/表创建问题

团队和锦标赛制作了一个新表来引用哪个团队属于哪个锦标赛和其他方式 - 这完全是我想要的。

我试图做与匹配和团队相同,为两者定义集合,但由于某种原因它使匹配中的单个属性,TeamId,这是一个问题,因为匹配应该能够存储多个一个团体。

Screenshots for clarity

在此先感谢。

+0

请在你的描述更加清楚。从问题陈述中可以得到很多东西。 –

+0

这就是一对多关系的工作原理。父id(团队id)作为外键存储在子对象(matchup)中。 –

+0

所以对不起Lakshmi - 我发现它很难说:( – Fearaz

回答

0

如果在同一个文件中有多个引用,则需要告知EF如何执行关系。我更喜欢流畅的代码如下:

修正模型:

public class Matchup 
{ 
    public int Id { get; set; } 

    public int WinnerId { get; set; } // FK by convention 
    public Team Winner { get; set; } 
    public Tournament Tournament { get; set; } 
    public ICollection<Team> Teams { get; set; } 
} 

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

    public ICollection<Player> Players{ get; set; } 
    public ICollection<Matchup> Matchups{ get; set; } 
    public ICollection<Matchup> MatchupWinners{ get; set; } 
    public ICollection<Tournament> Tournaments{ get; set; } 
} 


// Configure 1 to many 
modelBuilder.Entity<Matchup>() 
    .HasOptional(m => m.Winner) 
    .WithMany(p => p.MatchupWinners) 
    .HasForeignKey(p => p.WinnerId); 

// Configure many to many 
modelBuilder.Entity<Matchup>() 
     .HasMany(s => s.Teams) 
     .WithMany(c => c.Matchups) 
     .Map(t => 
       { 
        t.MapLeftKey("MatchupId"); 
        t.MapRightKey("TeamId"); 
        t.ToTable("MatchupTeam"); 
       }); 

但你也可以用注解做到这一点:

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

    public ICollection<Player> Players{ get; set; } 

    [InverseProperty("Teams")] 
    public ICollection<Matchup> Matchups{ get; set; } 

    [InverseProperty("Winner")] 
    public ICollection<Matchup> MatchupWinners{ get; set; } 

    public ICollection<Tournament> Tournaments{ get; set; } 
} 
+0

明白了 - Matchups集合和Winne上的InverseProperty在比赛中进行了诀窍。 谢谢你一大堆史蒂夫:) – Fearaz