EF 6.1 Code First - the number of columns specified must match the number of primary key columns

故事扮演 提交于 2019-12-11 13:47:37

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/25729984/ef-6-1-code-first-the-number-of-columns-specified-must-match-the-number-of-pri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!