2

我的用户表:

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);

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

当我尝试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”。

有什么建议么?

4

1 回答 1

6

您可以通过将[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);

不要忘记 中的反向导航属性的 lambda 表达式WithMany,如上所示,并删除 和 中的冗余UserConfig配置PollConfig

于 2013-08-10T22:42:23.207 回答