更新mvc4中的实体



我想更新数据库中的现有行,问题是我有4个属性,用户不应该更新。如果我尝试下面的代码,它抛出错误"具有相同键的对象已经存在于ObjectStateManager中。ObjectStateManager不能用相同的键跟踪多个对象。" thx

控制器

    [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>

具有相同密钥的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);
}

相关内容

  • 没有找到相关文章

最新更新