在ASP.NET MVC中保留数据

时间:2012-02-16 14:00:30

标签: c# asp.net-mvc entity-framework

我在使用ASP.NET MVC和Entity Framework更新和插入记录方面遇到了一些问题。

我有一个动态创建的表单(这是一个报表),可以有任何问题。我试图让用户编辑报告并提交更改,以便在数据库中更新。

我正在通过存储库从数据库中检索要编辑的报告,然后将其设置为ModeratorReport的实例。然后我更改属性的值并使用db.SaveChanges将更改保存到数据库。

问题在于它没有保存更改。

请有人可以告诉我我做错了什么吗?

以下是Edit动作:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(FormCollection formCollection, int moderatorReportId, string status)
    {
        ModeratorReport reportToEdit = repository.GetModeratorReportById(moderatorReportId);
        List<QuestionAnswer> originalReportAnswers = repository.GetAllModeratorReportAnswers(moderatorReportId, status).ToList();

        foreach (QuestionAnswer answer in originalReportAnswers) {
            reportToEdit.QuestionAnswers.Remove(answer);
        }

        int sectionID;
        int questionID;

        foreach (string key in formCollection.AllKeys)
        {
            var value = formCollection[key.ToString()];

            Match m = Regex.Match(key, "section(\\d+)_question(\\d+)");

            if (m.Success) {
                QuestionAnswer newAnswer = new QuestionAnswer();

                sectionID = Convert.ToInt16(m.Groups[1].Value.ToString());
                questionID = Convert.ToInt16(m.Groups[2].Value.ToString());

                newAnswer.ModeratorReportID = moderatorReportId;
                newAnswer.SectionID = sectionID;
                newAnswer.QuestionID = questionID;
                newAnswer.Answer = value;
                newAnswer.Status = "SAVED";
                reportToEdit.QuestionAnswers.Add(newAnswer);
            }
        }

        reportToEdit.Status = "SAVED";

        AuditItem auditItem = new AuditItem();
        auditItem.ModeratorReportID = moderatorReportId;
        auditItem.Status = "SAVED";
        auditItem.AuditDate = DateTime.Now;
        auditItem.Description = "The Moderator report..."
        auditItem.UserID = User.Identity.Name;
        reportToEdit.Audit.Add(auditItem);

        db.SaveChanges();

        return RedirectToAction("Details", new { id = moderatorReportId });
    }

1 个答案:

答案 0 :(得分:1)

问题似乎就是你没有将reportToEdit的EntityState设置为修改。像这样:

reportToEdit.Audit.Add(auditItem); 

reportToEdit.EntityState = EntityState.Modified;
db.SaveChanges();

有关EntityState枚举的详细信息,请参阅this MSDN article