I am unable to update the entity. Below is the code I used to update the entity. It works the first time its updated. But it fails the next time.
Generic method
public TEntity Update(TEntity entity)
{
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
return entity;
}
Controller
public IHttpActionResult Put(Invoice invoice)
{
return Ok(invoiceService.UpdateInvoice(invoice));
}
Service
public Invoice UpdateInvoice(Invoice invoice)
{
return _repo.Update(invoice);
}
The error that is coming.
System.InvalidOperationException: 'Attaching an entity of type 'Models.Invoice' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
Update: See below for the answer.