无法跟踪实体类型"BookLoan"的实例

Chr*_*son 6 c# asp.net-mvc entity entity-framework asp.net-core

我正在尝试更新实体,但我遇到了以下错误:

InvalidOperationException:无法跟踪实体类型"BookLoan"的实例,因为已经跟踪了具有相同键的此类型的另一个实例.添加新实体时,对于大多数键类型,如果未设置任何键,则将创建唯一的临时键值(即,如果为键属性指定了其类型的默认值).如果要为新实体显式设置键值,请确保它们不会与现有实体或为其他新实体生成的临时值发生冲突.附加现有实体时,请确保只有一个具有给定键值的实体实例附加到上下文.

我已经做了一些研究,从我可以告诉我,我显然试图跟踪已经跟踪的实体,_context.Update(bookloan);但我不知道该怎么做.

我要做的是更新我的数据库中的现有实体/记录.这里是get和post控制器,因为我不确定还有什么可以分享.

得到

    [HttpGet]
    public async Task<IActionResult> Return(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        if (isBookCheckedOut(id) == false)
        {
            //Not checked out
            return RedirectToAction("Index");
        }
        else
        {
            var bookloan = (from book in _context.Books.Where(b => b.BookId == id)
                        join loan in _context.BookLoans.Where(x => !x.ReturnedOn.HasValue) on book.BookId equals loan.BookID into result
                        from loanWithDefault in result.DefaultIfEmpty()
                        select new BookReturnViewModel
                        {
                            BookLoanID = loanWithDefault.BookLoanID,
                            BookID = book.BookId,
                            Title = book.Title,
                            StudentID = loanWithDefault == null ? null : loanWithDefault.StudentID,
                            StudentFristName = loanWithDefault == null ? null : loanWithDefault.Student.FirstName,
                            StudentLastName = loanWithDefault == null ? null : loanWithDefault.Student.LastName,
                            //Fines
                            CheckedOutOn = loanWithDefault == null ? (DateTime?)null : loanWithDefault.CheckedOutOn,
                            IsAvailable = loanWithDefault == null,
                            AvailableOn = loanWithDefault == null ? (DateTime?)null : loanWithDefault.DueOn
                        }).FirstOrDefault();

            if (bookloan == null)
            {
                return NotFound();
            }

            return View(bookloan);
        }
    }
Run Code Online (Sandbox Code Playgroud)

帖子:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Return(BookReturnViewModel model)
    {


        if (ModelState.IsValid && isBookCheckedOut(1) == true)
        {
            var bookloan = new BookLoan()
            {
                BookLoanID = model.BookLoanID,
                BookID = model.BookID,
                StudentID = model.StudentID,
                CheckedOutOn = (DateTime)model.CheckedOutOn,
                DueOn = (DateTime)model.AvailableOn,
                ReturnedOn = DateTime.Now
            };


            try
            {

                _context.Update(bookloan);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {

            }

            return RedirectToAction("Index");
        }
        else
        {

        }

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

小智 13

您的上下文已包含实体,因此创建新实体,根据实体的ID获取现有实体并更新其属性,然后保存

if (ModelState.IsValid && isBookCheckedOut(1) == true)
{
    // Get the existing entity
    BookLoan bookLoan = db.BookLoans.Where(x => x.BookLoanID == model.BookLoanID).FirstOrDefault();
    if (bookLoan != null)
    {
        bookLoan.BookID = model.BookID;
        bookLoan.StudentID = model.StudentID;
        .... // update other properties as required
        _context.Update(bookloan);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    ....
Run Code Online (Sandbox Code Playgroud)

附注:在返回视图时,使用它回传模型的良好做法return View(model);- 即使您没有(因为它们从中获取值ModelState),您的表单控件也会正确填充,但是如果您对模型属性有任何引用(例如<div>@Model.someProperty</div>)它会抛出异常.

  • 执行 db.BookLoans.Find(model.BookLoanID) 会*可能*更快,因为它会在转到数据库之前首先尝试从上下文中检索它 (2认同)
  • 如果没有一堆 `existingObject.Property1 = UpdatedObject.Property1` 的东西,你如何做到这一点? (2认同)