I'm developing an app for a Exams and other stuff... In my App I Add Questions and then i can add it to a Test. I'm also using Code First.
Here we have my Question Model:
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; }
}
And my Test Model:
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; }
}
I Used Fluent API for the Many to Many relationship.
modelBuilder.Entity<Question>()
.HasMany(question => question.Tests)
.WithMany(test => test.Questions)
.Map(ma =>
{
ma.MapLeftKey("QuestionId");
ma.MapRightKey("TestId");
ma.ToTable("QuestionTest");
});
And I'm Updating the Questions of a Test in this method.
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);
}
}
}
}
And when I Tried to save the database the application breaks and i get an error like this:
Violation of PRIMARY KEY constraint 'PK_dbo.QuestionTest'. Cannot insert duplicate key in object 'dbo.QuestionTest'. The duplicate key value is (1, 1).
I Was Following the Official Microsoft Documentation in: Microsoft Documentation MVC 5 Updating
And they said that we can modify a List just by changing his members and save it, but i get an error... Anyone know why? Thanks for reading! Hope you guys can help me.
After all the research and reading and trying a lot of things... I Just saw that mi List was not Virtual so that was the problem... I just answer if someone suffer the same thing...