从viewmodel更新数据库,但也添加新记录

时间:2012-07-19 15:26:33

标签: asp.net asp.net-mvc asp.net-mvc-3

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

当我将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 个答案:

答案 0 :(得分: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);