【问题标题】:Code First - Two foreign keys as primary keys, unable to add migrationCode First - 两个外键作为主键,无法添加迁移
【发布时间】:2013-08-10 22:04:32
【问题描述】:

我的用户表:

public class User
    {
        [Key]
        public int UserId { get; set; }

        public virtual ICollection<PollVote> PollVotes { get; set; }
    }

我的投票表:

public class Poll
    {
        [Key]
        public int PollId { get; set; }

        public virtual ICollection<PollVote> PollVotes { get; set; }
    }

我的投票表

public class PollVote
    {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]        
        public int VoteId { get; set; }

        [Key]
        public int PollId { get; set; }

        [Key]
        public int UserId { get; set; }

        public DateTime TimeVoted { get; set; }
        public int Answer { get; set; }

        public virtual Poll Poll { get; set; }
        public virtual User User { get; set; }
    }

我的配置:

//User config:
             this.HasMany(x => x.PollVotes)
                .WithRequired()
                .HasForeignKey(x => x.UserId)
                .WillCascadeOnDelete(false);

//Poll Config
            this.HasMany(x => x.PollVotes)
                .WithRequired()
                .HasForeignKey(x => x.PollId)
                .WillCascadeOnDelete(false);

//PollVote Config
            this.HasKey(x => x.UserId)
                .HasRequired(x => x.User)
                .WithMany()
                .HasForeignKey(x => x.UserId);
            this.HasKey(x => x.PollId)
                .HasRequired(x => x.Poll)
                .WithMany()
                .HasForeignKey(x => x.PollId);

关系是:一个投票可以有很多票,但一个用户只能给每个投票一票。

当我尝试在 PM-Console 中 Add-Migration 时收到此错误

\tSystem.Data.Entity.Edm.EdmAssociationEnd::多重性在关系“PollVote_Poll”中的角色“PollVote_Poll_Source”中无效。因为从属角色指的是关键属性,所以从属角色的多重性的上限必须是“1”。 \tSystem.Data.Entity.Edm.EdmAssociationEnd: : 多重性在关系“Poll_PollVotes”中的角色“Poll_PollVotes_Target”中无效。因为从属角色是指关键属性,所以从属角色的多重性的上限必须是'1'。

有什么建议吗?

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    您可以通过将[Column] 属性添加到数据注释来指定复合键...

        [Key, Column(Order = 1)]
        public int PollId { get; set; }
    
        [Key, Column(Order = 2)]
        public int UserId { get; set; }
    

    ...或者通过 Fluent API 使用匿名对象:

    this.HasKey(x => new { x.UserId, x.PollId });
    
    this.HasRequired(x => x.User)
        .WithMany(u => u.PollVotes)
        .HasForeignKey(x => x.UserId);
    
    this.HasRequired(x => x.Poll)
        .WithMany(p => p.PollVotes)
        .HasForeignKey(x => x.PollId);
    

    不要忘记WithMany中逆向导航属性的lambda表达式,如上图,去掉UserConfigPollConfig中的冗余配置。

    【讨论】:

    • 这会使数据库生成的 VoteId 字段变得多余吗?
    • @Colin:为了定义键和关系,是的。但也许他想有一些独特的计数器来为PollVotes 编号,无论出于何种原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2014-05-02
    • 2019-03-24
    相关资源
    最近更新 更多