Currently we're running a MySQL Database on a WampServer on localhost. We have a few classes and have mapped them to the database tables using POCO classes.
We have a repository for dealing with all creates, edits and deletes as is standard. We pass this repository a Question object, this question object has basic properties such as an id, text and also it contains a navigation property to link to all the answers to that question.
In the poco class of question all of the answers are stored as an ICollection. This has been working fine for weeks able to update and delete and create with no problems.
Now all of a sudden any time we try to edit a question it is leading to an exponential duplication of its answers, 2 became 4 which became 8 and before we knew it we had nearly 60k answers as we were trying to solve this problem.
The code in the repository for editing the question:
public void EditQuestion(Question question)
{
var tempquestion = Context.Questions.Single(q => q.Question_Id == question.Question_Id);
tempquestion.Question_Help = question.Question_Help;
tempquestion.Question_Text = question.Question_Text;
tempquestion.Question_Type = question.Question_Type;
context.SaveChanges();}
We've stepped through this so many times with breakpoints on every line, checking the answer property, it stays as the correct number throughout the entire process, then it hits context.saveChanges() and if we catch the result of that suddenly its duplicated.
Further Notes and requested code:
Yes i am using entity framework for this, i should have specified.
My poco class for the question is this:
public int Question_Id { get; set; }
public string Question_Text { get; set; }
public string Question_Help { get; set; }
public string Question_Type { get; set; }
[Display(Name = "Set ID")]
public int Set_Id { get; set; }
public Set Set { get; set; }
private ICollection<Answer> _answers;
public ICollection<Answer> Answers
{
get
{
if (_answers == null)
{
_answers = Arep.GetAnswers(this.Question_Id);
}
return _answers;
}
set
{
_answers = value;
}
} //a collection of answers belonging to this question
EDIT 2: I think i may now be a large step closer to the real issue. Thanks to the helpful link from CodeCaster i checked through my last queries, when it has 2 answers it only executes 2 insert statements, which is expected, but im ending up with 4 answers total, apparently the real issue here is that its adding new ones when answers are passed along with an edited question, which never used to happen.
Hoping the fix will be to send the edited question along with no answers tied to it, that way no new ones are inserted and no duplicates are made.