2012-03-14 107 views
0

我如何保存舊數據的操作[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; } 
} 

當我創建任務 - Spool.Weight改變 Task.Spool.Weight = Task.Spool.Weight - (Task.sheet_length * Task.sheets_num *任務。 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(它使用相同的密鑰對象)

+0

我不知道這樣的工作,但不能你只是在'task'更新'taskOld'與改變的值,然後'SaveChanges'? – 2012-03-14 14:11:32

+0

回頭看,有一件事你根本就不清楚 - 你是否試圖在編輯過程中保留舊任務並插入新任務?現在你的問題聽起來像是我重讀了它。 – Leniency 2012-03-14 14:49:38

回答

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),它會試圖做同樣的事情。

0

可以從寬如下代碼,或:

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