• This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts

  • kevin
    Keymaster
    Postcount 45

    Hi All,

    I want update a object with Entity Framework Core. I did with steps as below:

    1. Find object from database with Id
    2. Use Microsoft.EntityFrameworkCore.EntityState.Modified state to update

    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?


    kevin
    Keymaster
    Postcount 45

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

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.
Top