在mvc4中更新实体

时间:2014-03-28 20:12:48

标签: linq entity-framework asp.net-mvc-4

我想更新数据库中的现有行,问题是我有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>

1 个答案:

答案 0 :(得分: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);
}