【问题标题】:Code first Generating Extra Columns代码优先生成额外的列
【发布时间】:2016-05-01 06:35:04
【问题描述】:

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

【问题讨论】:

    标签: c# entity-framework code-first


    【解决方案1】:

    发生这种情况,因为FriendLinker 类有两个链接到Player 类,而Player 类只有一个链接,EF 对此有点困惑,结果出现了额外的列Player_PlayerId1,这列正是链接到Player(ICollection 属性,这就是为什么:当我执行 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; }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 2018-02-13
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多