0

我有一个包含项目列表的视图(可以通过 jQuery 动态添加)。

当我将视图模型 POST 回控制器时,如果代码找不到 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);
    }

谢谢你的帮助,

标记

4

1 回答 1

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(即db类型为ObjectContext),则应使用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);
于 2012-07-19T15:29:09.897 回答