代码首先生成额外的列

时间:2016-05-01 06:35:05

标签: c# entity-framework code-first

我有一组通过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

1 个答案:

答案 0 :(得分:2)

它发生了,因为FriendLinker类有两个指向Player类的链接,但是Player类只有一个链接而EF很少对它感到困惑,因此附加列{{1 }}出现,此列与Player_PlayerId1Player属性完全关联,这就是原因:当我执行player.Friends.add(..)时,playerId将插入到PlayerId1中。 )。您指定的另外两列被视为隐式链接到ICollection类。您可以通过在Player类声明中添加到FriendLinker类的第二个链接来修复它,并通过Player属性的构造函数参数指定此链接将与哪些具体属性相关:

InverseProperty