当尝试更新模型中的List时出现错误:违反PRIMARY KEY约束

时间:2016-10-28 20:41:47

标签: asp.net-mvc entity-framework relational-database updating

我正在开发一个考试和其他东西的应用程序...... 在我的应用程序中添加问题然后我可以将其添加到测试中。 我也在使用Code First。

这里有我的问题模型:

public class Question
{
    public Question() {
        this.Tests = new HashSet<Test>();
    }

    public int QuestionId { get; set; }
    [Display(Name = "Descripción")]
    public string QuestionDescription { get; set; }
    [Display(Name = "Competencia")]
    public int ProfiencyId { get; set; }

    public virtual Proficiency Profiency { get; set; }
    public virtual ICollection<Test> Tests { get; set; }
}

我的测试模型:

public class Test
{
    public Test() {
        this.Questions = new HashSet<Question>();
    }

    public int TestId { get; set; }
    [Display(Name = "Descripción")]
    public string TestDescription { get; set; }
    [Display(Name = "Tipo de evaluación")]
    public EVALUATE_TO EvaluateTo { get; set; }

    public ICollection<Question> Questions { get; set; }
}

我使用Fluent API来实现多对多关系。

modelBuilder.Entity<Question>()
            .HasMany(question => question.Tests)
            .WithMany(test => test.Questions)
            .Map(ma =>
            {
                ma.MapLeftKey("QuestionId");
                ma.MapRightKey("TestId");
                ma.ToTable("QuestionTest");
            });

我正在用这种方法更新测试问题。

private void UpdateTestQuestions(string[] selectedQuestions, Test testToUpdate)
    {
        if (selectedQuestions == null)
        {
            testToUpdate.Questions = new List<Question>();
            return;
        }

        var selectedQuestionsHS = new HashSet<string>(selectedQuestions);
        var testQuestions = new HashSet<int>
            (testToUpdate.Questions.Select(c => c.QuestionId));
        foreach (var question in ApplicationDbContext.Questions)
        {
            if (selectedQuestionsHS.Contains(question.QuestionId.ToString()))
            {
                if (!testQuestions.Contains(question.QuestionId))
                {
                    if (!testToUpdate.Questions.Contains(question)) {
                        testToUpdate.Questions.Add(question);
                    }
                }
            }
            else
            {
                if (testQuestions.Contains(question.QuestionId))
                {
                    testToUpdate.Questions.Remove(question);
                }
            }
        }
    }

当我试图保存数据库时应用程序中断,我得到一个错误:

违反PRIMARY KEY约束'PK_dbo.QuestionTest'。无法在对象'dbo.QuestionTest'中插入重复键。重复键值为(1,1)。

我正在关注以下官方Microsoft文档: Microsoft Documentation MVC 5 Updating

并且他们说我们可以通过更改他的成员并保存它来修改List,但是我收到错误... 谁知道为什么? 谢谢阅读!希望你们能帮助我。

1 个答案:

答案 0 :(得分:0)

经过所有研究和阅读并尝试了很多事情...... 我刚刚看到mi List不是虚拟的,所以这就是问题...... 如果有人遭受同样的事情,我只会回答......