2015-03-25 60 views
1
public ActionResult Event_History(int id = 0) 
    { 
     //set into false the active flag of the event 
     Events_Info_tbl events = db.Events_Info_tbl.Find(id); 
     events.is_active = false; 
     db.Entry(events).State = EntityState.Modified; 

     //set the category under this event into inactive 
     List<Events_Category_tbl> category = new List<Events_Category_tbl>(); 
     category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();   
     foreach(var i in category){ 
      Events_Category_tbl cat = new Events_Category_tbl(); 
      cat.is_active = false; 
      db.Entry(cat).State = EntityState.Modified; 
     } 

     db.SaveChanges(); 

     TempData["MessageAlert"] = "Event is save in history!"; 

     return RedirectToAction("Index"); 


    } 

Iam計劃設置爲非活動狀態,所有類別都屬於該特定事件,但是當我嘗試運行此代碼時顯示錯誤「具有相同鍵的對象已存在於ObjectStateManager。ObjectStateManager不能使用相同的密鑰跟蹤多個對象。「指向我的這部分代碼db.Entry(cat).State = EntityState.Modified;更新數據庫中的數據列表

+0

您不需要手動更改狀態,它由EF處理 – Peyman 2015-03-25 00:18:56

回答

0

下面的代碼嘗試創建新的對象,並保存在數據庫,所有新對象有這就是爲什麼給這個錯誤的編號相同:

Events_Category_tbl cat = new Events_Category_tbl(); 
cat.is_active = false; 
db.Entry(cat).State = EntityState.Modified; 

你並不需要創建新的對象,只需更新檢索的實體:

public ActionResult Event_History(int id = 0) 
{ 
    //set into false the active flag of the event 
    var events = db.Events_Info_tbl.Find(id); 
    events.is_active = false;   

    //set the category under this event into inactive 
    var category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();   
    foreach(var cat in category){ 
     cat.is_active = false; 
    } 

    db.SaveChanges(); 

    TempData["MessageAlert"] = "Event is save in history!"; 

    return RedirectToAction("Index"); 


} 
0
 foreach(var i in category){ 
     Events_Category_tbl cat = new Events_Category_tbl(); 
     cat.is_active = false; 
     db.Entry(cat).State = EntityState.Modified; 
    } 

這部分沒有任何意義。您不應創建Events_Category_tbl的新實例。

而應該只是

foreach(var i in category){ 
     i.is_active = false; 
    } 
0

類別表中的可重複自己....請更換:

db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList() 

db.Events_Category_tbl.Where(x=>x.events_info_id==id).Distinct().ToList() 

這樣,你將確保每個項目只重複一次