Context.SaveChanges()导致重复问题

时间:2012-07-24 10:28:52

标签: c# mysql entity-framework

目前我们在localhost上的WampServer上运行MySQL数据库。我们有几个类,并使用POCO类将它们映射到数据库表。

我们有一个存储库,用于处理标准的所有创建,编辑和删除。 我们将此存储库传递给一个Question对象,此问题对象具有基本属性,例如id,text,还包含一个导航属性,用于链接到该问题的所有答案。

在poco类问题中,所有答案都存储为ICollection。这已经好几周了,能够更新,删除和创建没有问题。

现在突然间我们试图编辑一个问题导致它的答案呈指数重复,2变为4变为8,在我们知道之前我们有近60k的答案,因为我们试图解决这个问题问题。

存储库中用于编辑问题的代码:

 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();}

我们已经多次使用断点检查了每一行,检查了answer属性,它在整个过程中保持正确的数字,然后它命中了context.saveChanges()并且如果我们捕获了结果突然间它重复了。

进一步说明和要求的代码:

是的我正在使用实体框架,我应该指定。

我的poco课程的问题是:

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

编辑2:我想我现在可以向真正的问题迈进一大步了。感谢CodeCaster提供的有用链接,我检查了我的最后一个查询,当它有2个答案时,它只执行2个插入语句,这是预期的,但最终总共有4个答案,显然这里真正的问题是它添加新的当答案与编辑过的问题一起传递时,这个问题从未发生过。

希望修复程序将发送编辑过的问题并且没有与之相关的答案,这样就不会插入新的问题而且不会重复。

2 个答案:

答案 0 :(得分:0)

不知道问题是什么,无法从你的问题中读出来,所以不知道这是否解决了问题,但我会像这样做POCO:

public class Question {
    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; }
    public virtual ICollection<Answer> Answers { get; set; }
}

答案是否有ID字段?我猜他们这样做,当他们与EF一起使用时。

答案 1 :(得分:0)

感谢CodeCaster提供的有关如何记录所有执行查询的有用提示,我能够看到正确的数量被添加。

问题在于它不应该一直在添加答案!但是因为每当我更新问题时问题属性都有答案,它会重新添加所有答案!因此,导致我看到正确的数字,以保存更改,但错误的数字后。

非常感谢CC!