2014-05-06 80 views
3

我是新來的MVC3 im試圖執行更新功能後編輯其中的內容兩個外鍵(BRANCH_ID,ITEM_MASTER_ID)。
問題IM branch_id或Item_master_id沒有改變該行被更新,但如果夷鍵改變其扔我一個錯誤,當面向簡單:如何使用entitystate.modified更新外鍵?

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

這裏是我的模型

public partial class MATERIAL 
{ 
    public int ID { get; set; } 
    public int ITEM_MASTER_ID { get; set; } 
    public int BRANCH_MASTER_ID { get; set; } 
    public string NAME { get; set; } 
    public string ADDRESS_DETAILS { get; set; } 

    public virtual BRANCH_MASTER BRANCH_MASTER { get; set; } 
    public virtual ITEM_MASTER ITEM_MASTER { get; set; } 
} 

我的編輯功能代碼

[HttpPost] 
public ActionResult Edit(MATERIAL material) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Entry(material).State = EntityState.Modified; 
     db.SaveChanges(); 
     int tempid = material.ID; 
     return RedirectToAction("listcontinue", new { id = tempid }); 

    } 
    return View(material); 
} 

幫助我執行更新,即使我的foreigns鍵已更改。

這裏是我的改進編輯代碼

public ActionResult Edit(MATERIAL material) 
    { 
     var temp = Convert.ToString(material.ITEM_NAME); 

     using (var context = new material_managementEntities()) 
     { 
      var temp1 = (from cs in context.ITEM_MASTER 
         where cs.ITEM_NAME == temp 
         select cs.ID).FirstOrDefault(); 
      material.ITEM_MASTER_ID = temp1; 
     } 

     var temp2 = Convert.ToString(material.ITEMGROUP); 

     using (var context = new material_managementEntities()) 
     { 
      var temp3 = (from cs in context.ITEM_GROUP_MASTER 
         where cs.ITEM_GROUP_NAME == temp2 
         select cs.ID).FirstOrDefault(); 
      material.ITEM_MASTER_ITEM_GROUP_MASTER_ID = temp3; 
     } 

     if (ModelState.IsValid) 
     { 
      db.MATERIALs.Attach(material); 
      db.Entry(material).State = EntityState.Modified; 
      db.SaveChanges(); 
      int tempid = material.ID; 
      return RedirectToAction("listcontinue", new { id = tempid }); 

     }   
     return View(material); 
    } 

回答

2

我想你忘了附上對象:

db.Materials.Attach(material); 
db.Entry(material).State = EntityState.Modified; 
db.SaveChanges(); 
+0

沒有chrfin即使在附加其不工作的問題後,這裏是我的外鍵chan ges和entity沒有采用新的外鍵標識 – Vikas

+0

奇怪 - 我在這裏成功地使用了類似的東西。你能說明你是如何在EF中設置實現的嗎? – ChrFin

+0

http://i.stack.imgur.com/rPAbH.png這裏是我的EF關係圖不要擔心abt剩餘的列我已經刪除了簡化的問題和許多關係是一對多 – Vikas

0

我想在上下文EF不知道外鍵,我有在我更新外鍵之前先使用包括:

db.Entry(team).State = EntityState.Modified; 
db.SaveChanges(); 

var updatedTeam = db.Teams.Include(x=> x.GameType).Where(x=> x.ID == team.ID).Single(); 
updatedTeam.GameType = db.GameTypes.Find(GameTypeId); 
db.SaveChanges();