2017-10-20 184 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