Home > Blockchain >  Trying to update a row value in SQL with ASP.NET Core 6
Trying to update a row value in SQL with ASP.NET Core 6

Time:01-29

I am trying to update a row value in SQL with my DbContext in ASP.NET Core 6. The column is named TextField but I get this error:

InvalidOperationException: The instance of entity type 'TextField' 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.

Here is my code:

[HttpPost]
public IActionResult UploadText(string newText, string section)
{
    MgvaKrantransportContext DBContext = new MgvaKrantransportContext();

    var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();

    TextField newTextField = new TextField();

    foreach (var textField in textSelection)
    {
        newTextField = new TextField() { Id = textField.Id, Section = section, TextContent = newText };
    }

    DBContext.Entry(newTextField).Property(x => x.TextContent).IsModified = true;
    DBContext.SaveChanges();

    return RedirectToAction("Index");
}

Thanks in advance

Best regards Max

CodePudding user response:

If you want to update using a stub entity, don't query the database first. Simply remove this line

 var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();

Alternatively, update the returned TextField(s) and don't create a new one.

eg

foreach (var textField in textSelection)
{
    textField.TextContent = newText ;
}
DBContext.SaveChanges();
  •  Tags:  
  • Related