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>
thx it works :) – Asdfsdfdsfsd