0

我得到了这个错误

ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。

只因为这条线

oldProject = db.Projectes.Find(project.ID);

我需要它以便在编辑之前获取对象,然后比较编辑前后的值变化,我在第三个 if 语句(比较一个值)和“SFSiteEmailSend.ProjectEdited”函数中进行只检查更改并发送有关它的电子邮件。

顺便说一句,我从不更改“旧项目”,即使我删除了所有电子邮件功能和第三个(最后一个)if 语句,错误仍然存​​在。

        // POST: /Project/Edit/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Project project)
    {
        if (ModelState.IsValid)
        {  

            // For Email Send - start
            string UrlProject = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("Detail", "Project", new { id = project.ID });
            Project oldProject = new Project();
            Project newProject = new Project();
            newProject = project;
            oldProject = db.Projectes.Find(project.ID);
            SFSiteEmailSend.ProjectEdited(oldProject, newProject, UrlProject);
            // For Email Send - end

            if (oldProject.Finished == false && newProject.Finished == true)
            {
                project.DateFinished = DateTime.Now;
            }
            db.Entry(project).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(project);
    }
4

3 回答 3

1

在保存更改之前尝试
project.entitykey = oldproject.entitykey

于 2014-05-26T19:15:17.593 回答
1

您的代码充满了冗余。去掉其中的一些,应该更容易发现错误:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Project newProject)
{
   if (ModelState.IsValid)
   {
       string UrlProject = Request.Url.GetLeftPart(UriPartial.Authority) 
                         + Url.Action("Detail", "Project", new { id = newProject.ID });

       //both oldProject and newProject have the same Key but only oldProject 
       //is attached
       Project oldProject = db.Projectes.Find(newProject.ID);

       SFSiteEmailSend.ProjectEdited(oldProject, newProject, UrlProject);

       if (!oldProject.IsFinished && newProject.IsFinished )
          newProject.DateFinished = DateTime.Now;

       //now you try to attach another project with the same Key. 
       //It will fail when you call SaveChanges         
       db.Entry(newProject).State = EntityState.Modified;

      //This is an option:
      d.Entry(oldProject).State = EntityState.Detached;

      db.SaveChanges();
      return RedirectToAction("Index");
   }
   return View(newProject);
}

或者您可以首先加载- 正如您已经发现的oldProject那样AsNoTracking

于 2013-10-18T03:40:41.480 回答
0

我找到了解决方案

反而

public ActionResult Edit(Project project)
    {
     Project beforeEditProject = db.Projectes.Find(project.ID);
     .... 
    }

}

利用

public ActionResult Edit(Project project)
        {
          Project beforeEditProject = db.Projectes.AsNoTracking().First(p => p.ID == project.ID);
          .....
        }
于 2013-10-17T22:36:16.117 回答