- This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
Viewing 2 posts - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.
Hi All,
I want update a object with Entity Framework Core. I did with steps as below:
I just get errors message: The instance of entity type cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked
Anybody can help me?
You can use AsNoTracking() in Microsoft.EntityFrameworkCore to clear track object before update. You can see sample code below:
[HttpPost]
[Route(“edit/{id}”)]
public IActionResult Edit(int id, Account account)
{
if (account.Password == null)
{
account.Password = db.Account.AsNoTracking().SingleOrDefault(a => a.Id == id).Password;
}
else
{
account.Password = BCrypt.Net.BCrypt.HashPassword(account.Password);
}
db.Entry(account).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“index”, “account”);
}