2014-03-28 67 views
0

我想更新數據庫中的現有行,問題是我有4個屬性,用戶不應該更新。如果我嘗試下面的代碼,它會拋出錯誤:「ObjectStateManager中已存在具有相同鍵的對象,ObjectStateManager無法使用同一個鍵跟蹤多個對象。」 THX在mvc4更新實體

控制器

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Edit([Bind(Include = "Id, Name, Author, Price")]Book book) 
    { 

      book.NewBookId = db.Book.Single(x => x.Id == book.Id).NewBookId; 
      book.UsedBookId = db.Book.Single(x => x.Id == book.Id).UsedBookId; 
      book.TextBook = db.Book.Single(x => x.Id == book.Id).TextBook; 
      book.WorkBook = db.Book.Single(x => x.Id == book.Id).WorkBook; 
      if (ModelState.IsValid) 
      { 
       db.Book.Attach(book); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      return View(book); 

    } 

查看

@Html.HiddenFor(model => model.Id) 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Author) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Author) 
     @Html.ValidationMessageFor(model => model.Author) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Name) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Name) 
     @Html.ValidationMessageFor(model => model.Name) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Price) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Price) 
     @Html.ValidationMessageFor(model => model.Price) 
    </div> 

    <p> 
     <input type="submit" value="Save" /> 
    </p> 
</fieldset> 

回答

0

Book使用相同的密鑰已經存在。

您正在嘗試更新現有書籍,對吧?

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit([Bind(Include = "Id, Name, Author, Price")]Book model) 
{ 
    if (ModelState.IsValid) 
    { 
     var book = db.Book.SingleOrDefault(x => x.Id == model.Id); 
     if(book != null) 
     { 
      book.Name = model.Name; 
      book.Author = model.Author; 
      book.Price= model.Price; 

      db.SaveChanges(); 

      return RedirectToAction("Index"); 
     } 

     ModelState.AddModelError("Id", "Couldn't find book id.") 
    } 

    return View(model); 
} 
+0

thx it works :) – Asdfsdfdsfsd