2014-03-28 2 views
0

데이터베이스의 기존 행을 업데이트하려는 경우 사용자가 업데이트하지 말아야 할 4 가지 속성이 있습니다. 나는 코드를 bellow 시도하면 "같은 키를 가진 객체가 ObjectStateManager에 이미 존재합니다 .ObjectStateManager는 동일한 키를 가진 여러 객체를 추적 할 수 없습니다." 들으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 작동 :) – Asdfsdfdsfsd

관련 문제