无法更新 asp.net-core 2.2 c# 中的记录

Unable to update a record in asp.net-core 2.2 c#

我正在尝试按如下方式更新项目的记录

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Label,Description,LessonId,Position,FileName,Format,Status")] Content content)
{
      if (id != content.Id)
      {
         return NotFound();
      }

      var existingContent = await _context.Contents.FindAsync(id).ConfigureAwait(false);

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

      string fileToDelete = null;

      if (ModelState.IsValid)
      {
          try
          {

            if (Request.Form.Files["FileName"] != null)
            {
               IFormFile uploadedFile = Request.Form.Files["FileName"];
               var lesson_mimetype = uploadedFile.ContentType;

               string[] extensions = new string[] { ".jpeg", ".jpg", ".gif", ".png", ".mp4", ".mp3", ".pdf" };

               ResponseMsg fileTypeValidationMsg = FileUploadHelper.ValidateFileExtension(uploadedFile, extensions);

               if (!fileTypeValidationMsg.ResponseStatus)
               {
                   ModelState.AddModelError("FileName", fileTypeValidationMsg.ResponseDescription);
               }

               ResponseMsg filesizeValidationMsg = FileUploadHelper.ValidateFilesize(uploadedFile, 200);

               if (!filesizeValidationMsg.ResponseStatus)
               {
                   ModelState.AddModelError("FileName", filesizeValidationMsg.ResponseDescription);
               }

               if (content.Format == ResourceFormat.Text)
               {
                   string desiredUploadDirectory = "TextResources";

                   string lesson_file_name = await uploadHelper.SaveFileAsync(Request.Form.Files["FileName"], desiredUploadDirectory).ConfigureAwait(false);

                   existingContent.TextFileUrl = desiredUploadDirectory + "/" + lesson_file_name;
                   existingContent.FileName = lesson_file_name;
                   fileToDelete = existingContent.TextFileUrl;
                   }
                   else
                   {
                      string desiredUploadDirectory = "MultimediaResources";

                      string lesson_file_name = await uploadHelper.SaveFileAsync(Request.Form.Files["FileName"], desiredUploadDirectory).ConfigureAwait(false);

                      existingContent.MultiMediaFileUrl = desiredUploadDirectory + "/" + lesson_file_name;
                      existingContent.FileName = lesson_file_name;
                      fileToDelete = existingContent.MultiMediaFileUrl;
                   }

              }

              existingContent.LastUpdated = DateTime.Now;
              existingContent.Label = content.Label;
              existingContent.Description = content.Description;
              existingContent.LessonId = content.LessonId;
              existingContent.Position = content.Position;
              existingContent.Status = content.Status;
              existingContent.Format = content.Format;
              //_context.Update(existingContent); Now removed for the code to work

              await _context.SaveChangesAsync().ConfigureAwait(false);

              if (fileToDelete != null)
              {
                 System.IO.File.Delete(fileToDelete);
              }
                 return RedirectToAction(nameof(Index));
              }
              catch (Exception e)
              {
                 ModelState.AddModelError("", e.Message);
              }
       }

       ViewData["LessonId"] = new SelectList(_context.Lessons, "Id", "Label", content.LessonId);

       return View(content);
}

但问题是,当我提交更新表单时,我收到以下错误消息

The instance of entity type 'Content' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

我不知道如何解决这个问题。如果有任何指导,我将不胜感激。

在大多数情况下,EF 会自动检测哪些字段需要更新,在上下文中有一个 update 函数(需要一个实体)是一个危险信号,表示您正在尝试做一些不是必需的。

EF 在幕后做了很多事情,因此您不必考虑它们。这是其中之一。

我怀疑您读过一篇非常古老的博客,讲述了 10 年前某人如何不得不做一些事情让 EF 更新记录。

此外,从您的上下文 class 中删除 update 函数,以免其他人被它绊倒。