Code First - 两个外键为主键,无法添加迁移

Lar*_*ars 2 entity-framework ef-code-first entity-framework-migrations

我的用户表:

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

        public virtual ICollection<PollVote> PollVotes { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的投票表:

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

        public virtual ICollection<PollVote> PollVotes { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的投票表

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; }
    }
Run Code Online (Sandbox Code Playgroud)

我的配置:

//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);
Run Code Online (Sandbox Code Playgroud)

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

当我尝试Add-Migration在 PM-Console 中时出现此错误

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

有什么建议?

Sla*_*uma 5

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

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

    [Key, Column(Order = 2)]
    public int UserId { get; set; }
Run Code Online (Sandbox Code Playgroud)

...或通过使用带有 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);
Run Code Online (Sandbox Code Playgroud)

不要忘记在逆导航属性的lambda表达式WithMany,如上所示,并且移除在冗余配置UserConfigPollConfig