SaveChanges无法修改数据

时间:2014-10-13 17:51:04

标签: asp.net-mvc entity-framework ef-code-first

当我尝试保存新的Student对象时。它工作正常,但当我试图修改数据时,它不会更新数据。相反,SaveChanges不会抛出任何错误。

我正在使用代码第一种方法(使用mysql提供程序),这里它是完整的源代码。

https://www.dropbox.com/s/e34frntq8u5gsmh/SchoolManagementSystem.rar?dl=0

我疲惫的代码就是这样:

public ActionResult Create(Student student, HttpPostedFileBase Image)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    student = db.Students.Find(student.ID);
                    if (student.ID > 0)
                    {
                        db.Entry(student).State = EntityState.Modified;                        
                        db.SaveChanges();
                    }
                    else
                    {
                        if (student.Basic == null) student.Basic = new BasicInformation();
                        if (Image != null && Image.ContentLength > 0)
                        {
                            student.Basic.PictureUrl = Image.FileName;
                            string path = Server.MapPath(("~/Images/"));
                            Image.SaveAs(path + Image.FileName);
                        }

                        db.Students.Add(student);
                        db.SaveChanges();
                    }
                    return RedirectToAction("StudentList");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(student);
        }

2 个答案:

答案 0 :(得分:1)

这似乎是修改方案:

if (student.ID > 0)
                {
                    db.Entry(student).State = EntityState.Modified;                        
                    db.SaveChanges();
                }

消除这行代码:

db.Entry(student).State = EntityState.Modified;  

而是添加使用新修改值更新对象的代码。

希望这有帮助。

答案 1 :(得分:1)

通过这一行

student = db.Students.Find(student.ID);

您覆盖进入该方法的student并且您将丢失所有更改。你可以做两件事:

  1. 仅删除该行。您的代码现在会将修改后的student附加为EntityState.Modified

  2. 从数据库中获取原始学生并将修改后的值复制到其中:

    var studentOrg = db.Students.Find(student.ID);
    db.Entry(studentOrg).CurrentValues.SetValues(student);
    
  3. (两个SaveChanges次调用都可以移到return RedirectToAction...

    之前

    选项1将生成一个包含所有Student个字段的更新语句,但不能进行往返以获取原始记录。

    选项2具有此往返,但仅更新已修改的字段。当审计更改或最小化并发时,这(选项2)可能是有益的。