Я разрабатываю приложение для экзаменов и других материалов ... В моем приложении я добавляю вопросы, а затем могу добавить его в тест. Я также использую Code First.При попытке обновить список в модели возникла ошибка: Нарушение ограничения PRIMARY KEY
Здесь мы имеем мой вопрос Модель:
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).
I Was После официальной документации Microsoft в: Microsoft Documentation MVC 5 Updating
И они сказали, что мы можем изменить список просто путем изменения его членов и сохранить его, но я получаю сообщение об ошибке ... Кто-нибудь знает, почему ? Спасибо за чтение! Надеюсь, вы, ребята, можете мне помочь.