“编辑”操作,保存旧数据

时间:2012-03-14 14:01:15

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

如何保存旧数据[post]编辑?

我有这两个模型:

public class Task
{
    public int ID { get; set; }
    public int sheet_length { get; set; }
    public int sheets_num { get; set; }

    [Required]
    public int spoolID { get; set; }

    [ForeignKey("spoolID")]
    public virtual Spool Spool { get; set; }
}

public class Spool
{
    public int ID { get; set; }
    public string name { get; set; }
    public int weight { get; set; }
    public int weight_meter { get; set; }
    public virtual ICollection<Task> Tasks { get; set; }
}

当我创建Task - Spool.Weight更改时     Task.Spool.Weight = Task.Spool.Weight - (Task.sheet_length * Task.sheets_num * Task.Spool.weight_meter)

当我编辑任务时 - 我想这样做:

TaskOld.Spool.Weight = TaskOld.Spool.Weight + (TaskOld.sheet_length * TaskOld.sheets_num * TaskOld.Spool.weight_meter)

Task.Spool.Weight = Task.Spool.Weight - (Task.sheet_length * Task.sheets_num * Task.Spool.weight_meter)

但是当我尝试在编辑操作中获取旧数据时

[HttpPost]
public ActionResult Edit(Task task)
{
    if (ModelState.IsValid)
    {
        taskOld = dbContext.Tasks.Single (t => t.ID == task.ID);

        ////some code

        db.Tasks.Attach(task);
        db.SaveChanges();
        return RedirectToAction("Index", "Task", new { id = task.orderID });
    }
 ///some code }  

我收到一个ObjectStateManager错误(它的对象具有相同的键)

2 个答案:

答案 0 :(得分:1)

附加新任务时会出现问题。

if (ModelState.IsValid)
{
    taskOld = dbContext.Tasks.Single (t => t.ID == task.ID);

    ////some code

    // Error here! db.Tasks already contains something for the Id
    // Can't have two tasks with the same Id.  Attach doesn't update the
    // existing record, but adds the 'task' to the object graph for tracking.
    db.Tasks.Attach(task);

    db.SaveChanges();
    return RedirectToAction("Index", "Task", new { id = task.orderID });
}

两者都具有相同的Id,并且ObjectStateManager无法跟踪具有相同Id的同一对象中的两个。

更常规的方法是将任务输入映射到taskOld:

if (ModelState.IsValid)
{
    taskOld = dbContext.Tasks.Single (t => t.ID == task.ID);

    // ... Some code ...

    // taskOld is already attached to the DbContext, so just map the updated
    // properties.
    taskOld.Property1 = task.Property1;
    taskOld.Property2 = task.Property2;
    ...

    db.SaveChanges();
    return RedirectToAction("Index", "Task", new { id = task.orderID });
}

或者,不是单独分配属性,而是可以调用UpdateModel(taskOld),它会尝试执行相同的操作。

答案 1 :(得分:0)

您可以关注宽恕代码,或:

[HttpPost]
public ActionResult Edit(Task t)
{
    if (ModelState.IsValid)
    {
        db.Entry(t).State = EntityState.Modified;
        db.SaveChanges();
    }
    return View(t);
}