2012-07-19 97 views
0

我有一個視圖,它有一個項目列表(可以通過jQuery動態添加)。從viewmodel更新數據庫,但也添加新的記錄

當我將viewmodel返回給控制器時,如果代碼找不到ID,如何插入新項目並將它們保存到數據庫。

我最初的代碼如下 - 更新被保存,但新的項目將不保存:

// 
    // POST: /Objective/Edit/model 
    [HttpPost] 
    public ActionResult Edit(ObjectivesEdit model) 
    { 
     if (model.Objectives != null) 
     { 
      foreach (var item in model.Objectives) 
      { 
       // find the database row 
       Objective objective = db.objectives.Find(item.ID); 
       if (objective != null) 
       { 
        // Set the database row to the posted values 

        objective.objective = item.objective; 
        objective.score = item.score; 
        objective.possscore = item.possscore; 
       } 
       else // database item not found, so add a new item 
       { 
        // add a new objective 
        // This doesn't seem to add/save a new record 
        Objective obj = new Objective(); 
        obj.objective = item.objective; 
        obj.score = item.score; 
        obj.possscore = item.possscore; 
       } 
      } 
      // Save the changes to the database 
      db.SaveChanges(); 
     } 
     return View(model); 
    } 

感謝您的幫助,

馬克

回答

1

你不加新創建的目標對您的情況。

else // database item not found, so add a new item 
{ 
    // add a new objective 
    // This doesn't seem to add/save a new record 
    Objective obj = new Objective(); 
    obj.objective = item.objective; 
    obj.score = item.score; 
    obj.possscore = item.possscore; 

    // Missing line. 
    db.objectives.Add(obj); 
} 

如果你正在使用EF 4.0(即dbObjectContext型的),你應該使用db.AddObject(obj)

根據您的意見更新:
一種方法是在保存更改後檢索所有添加的項目。另一種方法是在創建新目標時修改模型。修改的部分都標有*:

foreach (var item in model.Objectives.ToList()) // *:Notice the ToList() 
{ 
    // find the database row 
    Objective objective = db.objectives.Find(item.ID); 
    if (objective != null) 
    { 
     // Set the database row to the posted values 

     objective.objective = item.objective; 
     objective.score = item.score; 
     objective.possscore = item.possscore; 
    } 
    else // database item not found, so add a new item 
    { 
      // add a new objective 
      // This doesn't seem to add/save a new record 
      Objective obj = new Objective(); 
      obj.objective = item.objective; 
      obj.score = item.score; 
      obj.possscore = item.possscore; 

     db.AddObject(obj) 
     // Save the changes to the database 
     db.SaveChanges(); // *: save in loop to get thee ID. 

     item.ID = obj.ID; // *: assign the ID to the model. 
    } 
} 

return View(model); 
+0

乾杯 - 我知道它必須是一些簡單的像那...謝謝你,馬克 – Mark 2012-07-19 15:43:02

+0

喜 - 一個跟進查詢 - 當我回來查看(模型);無論如何,我可以得到它返回模型,包括主鍵的新數據庫ID - 因爲它似乎剛剛返回0 - 這不是什麼顯然保存到數據庫?謝謝,Mark – Mark 2012-07-19 15:49:45

+0

完美 - 再次感謝你@Kamyar – Mark 2012-07-20 07:10:13

相關問題