1

I am running into the following error while trying to migrate a database in Entity Framework.

The specified association foreign key columns 'question_set_id' are invalid. The number of columns specified must match the number of primary key columns.

I dropped the original primary key QuestionSetId and created a composite key relationship. The columns in the composite key relationship also map to foreign keys. I'm not sure what the issue is.

Here is the associated entity.

public class QuestionSet
{
    [Key, Column(Order = 1)]
    public long TitleId { get; set; }

    [ForeignKey("TitleId")]
    public virtual Title Title { get; set; }

    [Key, Column(Order = 0)]
    public long ReviewCycleId { get; set; }

    [ForeignKey("ReviewCycleId")]
    public virtual ReviewCycle ReviewCycle { get; set; }

    public virtual List<Question> Questions { get; set; }
}

The DbContext has:

    modelBuilder.Entity<QuestionSet>()
            .HasMany(c => c.Questions)
            .WithMany(c => c.QuestionSets)
                .Map(x => x.ToTable("QUESTION_SET_QUESTION")
                    .MapLeftKey("question_set_id")
                    .MapRightKey("question_id"))
        ;
Sigotron
  • 75
  • 2
  • 6
  • It seems to me that the error is generated from the `Question` Entity. This Entity should have a composite foreign key to `QuestionSet`. It seems that `Question` has question_set_id as the foreign key for its `QuestionSet`though. – Dabblernl Sep 08 '14 at 19:52
  • Thanks I'll look into that possibility. I've discovered some other issues due the the fact that it is a many to many relationship. I'll edit my post with more information after I look into it further. – Sigotron Sep 08 '14 at 20:33
  • There you have it: `QuestionSet` has a composite primary key and you are specifying a single foreign key in your fluent API code for the Question_Set_Question junction table. – Dabblernl Sep 09 '14 at 04:53

1 Answers1

4

The QuestionSet has two keys, but the MapLeftKey of QuestionSet only spefified one key.

MapLeftKey("question_set_id")

Replace it with something like this:

MapLeftKey(new []{ "question_set_review_cycle_id", "question_set_title_id" })

The first key is ReviewCycleId (Column's Order 0), the second key is TitleId (Column's Order 1).

It should fix the problem, unless the Question also has two keys.

Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67