【问题标题】:Unable to update a record in asp.net-core 2.2 c#无法更新asp.net-core 2.2 c#中的记录
【发布时间】:2019-07-29 14:20:52
【问题描述】:

我正在尝试如下更新一个项目的记录

[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);
}

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

无法跟踪实体类型“内容”的实例,因为已经在跟踪另一个具有相同键值 {'Id'} 的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。

我不知道如何解决这个问题。我会很感激任何指导。

【问题讨论】:

标签: c# asp.net-core-2.2 ef-core-2.2


【解决方案1】:

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

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

我怀疑您阅读了一篇非常古老的博客,内容是关于 10 年前某人如何不得不做一些事情来让 EF 更新记录。

另外,从你的上下文类中删除 update 函数,这样就不会有人绊倒它了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2020-02-06
    • 2019-08-28
    • 2019-03-14
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多