2014-10-01 260 views
0

我得到这个一般性错误: -实体框架更新实体错误

Additional information: Attaching an entity of type 'entity' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate

及其对线之下发生当实体正在试图改变其状态。

public void InsertOrUpdate(T entity) 
    { 
     if (entity.Id == default(int)) 
     { 
      entity.Created = DateTime.Now; 
      entity.LastEdit = DateTime.Now; 

      Context.Initial.Add(initial); 
     } 
     else 
     { 
      entity.LastEdit = DateTime.Now; 
      Context.Entry(entity).State = System.Data.Entity.EntityState.Modified; 
     } 
    } 

不过,我得到它的时候我

  • 刷新初始化视图中的储存库的情况下,即。
  • 使用正确安装,而不是Context.T.Attach(entity)

当我不改变的状态信息或使用连接,它不进行任何更新。

这里是我的控制器代码

[HttpPost] 
[Authorize] 
public ActionResult Create(NewViewModel viewModel) 
{ 
    if (ModelState.IsValid) 
    { 
     m_CTS.InsertOrUpdate(viewModel.entity); 
     m_CTS.Save(); 

     // My big problem is that the Primary key that 
     // was generated doesnt come back from the view 
     // once edited, so I have created a property in 
     // the viewmodel to handle this 

     viewModel.ID = viewModel.entity.Id; 

     return RedirectToAction("Edit", new { id = viewModel.entity.Id }); 
    } 
    else 
    { 
     return View("New", viewModel); 
    } 
} 

[HttpGet] 
[Authorize] 
public ViewResult Edit(int id) 
{ 
    // Getting this from the same context of when it was created 
    viewModel.entity = respoitory.Find(id); 

    return View(viewModel); 
} 

[HttpPost] 
[Authorize] 
public ActionResult Edit(NewViewModel viewModel) 
{ 
    // Could be the problem : As I said above the ID on the entity.id 
    // never comes back from the view (because I am using a viewmodel?) 
    // So I need to assign the ViewModel ID to the entity model id 
    // before I try and update it 

    viewModel.entity.Id = viewModel.ID; 

    m_CTS.InsertOrUpdate(viewModel.entity); 
    m_CTS.Save(); 

    return RedirectToAction("Edit", new { id = viewModel.entity.Id }); 
} 

是否有一个原因,我与上面的代码得到这个错误?

感谢

回答

1

你有你的代码的注释中发现的问题:

 // My big problem is that the Primary key that 
     // was generated doesnt come back from the view 
     // once edited, so I have created a property in the viewmodel to handle this 

为了解决这个问题,添加@Html.HiddenFor(m => m.Id)到您的视图。现在,当您发布到控制器时,您的视图模型参数将包含您首先发送给视图的Id字段。

+0

谢谢,我仍然得到相同的错误的ID现在回来的POST现在感谢.. – user3428422 2014-10-01 14:36:39

+0

我不明白这个问题,然后。哪种控制器方法导致异常? – 2014-10-01 14:59:50

+0

我发现了一个解决方案,当我第一次从上下文中检索实体时,我使用了AsNoTracking(),并不确定这是否是绝对正确的解决方案,到目前为止,当我完成测试时,将会发布。欢呼声 – user3428422 2014-10-01 15:57:18