2016-05-01 16 views
1

我有一組玩家通過FriendLinker表連接在一起。代碼第一個生成額外的列

該表將兩個玩家聯繫在一起(在這種情況下,它的玩家 - >朋友)。我在下面的方式播放器設置:

public class Player 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    [Key, Column(Order=0)] 
    public Guid PlayerId { get; set; } 

    public virtual ICollection<FriendLinker> Friends { get; set; } 

    [Required] 
    public string Password { get; set; } //Will be switched to byte[] for hash 

    [MaxLength(100)] 
    [Index(IsUnique = true)] 
    public string Username { get; set; } 
} 

和連接表被設置這​​樣的:

public class FriendLinker 
{ 
    [Key] 
    public int FriendLinkerId { get; set; } 

    [Required] 
    public Player Player { get; set; } 

    [Required] 
    public Player Friend { get; set; } 
} 

然而,這產生了以下遷移:

CreateTable(
"dbo.FriendLinkers", 
c => new 
{ 
    FriendLinkerId = c.Int(nullable: false, identity: true), 
    Player_PlayerId = c.Guid(), 
    Friend_PlayerId = c.Guid(nullable: false), 
    Player_PlayerId1 = c.Guid(nullable: false), 
}) 
.PrimaryKey(t => t.FriendLinkerId) 
.ForeignKey("dbo.Players", t => t.Player_PlayerId) 
.ForeignKey("dbo.Players", t => t.Friend_PlayerId, cascadeDelete: false) 
.ForeignKey("dbo.Players", t => t.Player_PlayerId1, cascadeDelete: false) 
.Index(t => t.Player_PlayerId) 
.Index(t => t.Friend_PlayerId) 
.Index(t => t.Player_PlayerId1); 

的結果會創建一個額外的列Player_PlayerId1。當我做player.Friends.add(..)時,playerId被插入到PlayerId1中。

我該怎麼做才能防止產生額外的列PlayerId1

回答

2

它發生,因爲FriendLinker類有兩個鏈接Player類,但Player類只有一個鏈接和EF有點困惑了,結果其他列Player_PlayerId1出現,此列正好掛PlayerICollection財產,這就是爲什麼:當我做player.Friends.add(..)時,playerId被插入PlayerId1.)。您指定的另外兩列,被視爲與Player類隱含關聯。您可以通過Player類聲明添加第二個鏈接FriendLinker類修復它,並指定到具體的屬性這個鏈接將被InverseProperty屬性的構造函數的參數來相關:

public class Player 
{ 
    [InverseProperty("Player")] 
    public virtual ICollection<FriendLinker> Players { get; set; } 

    [InverseProperty("Friend")] 
    public virtual ICollection<FriendLinker> Friends { get; set; } 

    [Required] 
    public string Password { get; set; } //Will be switched to byte[] for hash 

    [MaxLength(100)] 
    [Index(IsUnique = true)] 
    public string Username { get; set; } 
}