尝试使用 ASP.NET Core 6 更新 SQL 中的行值
Trying to update a row value in SQL with ASP.NET Core 6
我正在尝试用 ASP.NET 核心 6 中的 DbContext
更新 SQL 中的行值。该列名为 TextField
但我收到此错误:
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.
这是我的代码:
[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");
}
提前致谢
问候 Max
如果要使用存根实体进行更新,请不要先查询数据库。只需删除此行
var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();
或者,更新返回的 TextField 并且不创建新的。
例如
foreach (var textField in textSelection)
{
textField.TextContent = newText ;
}
DBContext.SaveChanges();
我正在尝试用 ASP.NET 核心 6 中的 DbContext
更新 SQL 中的行值。该列名为 TextField
但我收到此错误:
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.
这是我的代码:
[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");
}
提前致谢
问候 Max
如果要使用存根实体进行更新,请不要先查询数据库。只需删除此行
var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();
或者,更新返回的 TextField 并且不创建新的。
例如
foreach (var textField in textSelection)
{
textField.TextContent = newText ;
}
DBContext.SaveChanges();