2
votes

My User table:

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

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

My Poll table:

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

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

My PollVote table

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

My Configurations:

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

The relation is: One Poll can have many votes, but a User can only give one vote to every poll.

I get this error when i try to Add-Migration in PM-Console

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'PollVote_Poll_Source' in relationship 'PollVote_Poll'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'. \tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Poll_PollVotes_Target' in relationship 'Poll_PollVotes'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

Any suggestions?

1

1 Answers

5
votes

You specify a composite key by either adding the [Column] attribute to the data annotations...

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

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

...or by using an anonymous object with 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);

Don't forget the lambda expressions for the inverse navigation properties in WithMany, as shown above, and remove the redundant configurations in UserConfig and PollConfig.