2014-10-01 258 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