efcore icon indicating copy to clipboard operation
efcore copied to clipboard

context.Update causes DELETE instead of UPDATE

Open MS699 opened this issue 2 years ago • 1 comments

Describe what is not working as expected

First I update an entity, and it works as expected. However, when something fails after the update, I update the entity again with its original values. When I update the entity for a second time it deletes the entity, instead of updating.

I do this with other entities as well, but only this one gets deleted. The only difference between this entity and the others is that this one is an abstract entity with 2 derived entities.

AbstractEntity original = new();
AbstractEntity entity = new();
bool succeeded = false;

try {
  original = await _context.Entity.AsNoTracking().FirstOrDefaultAsync(x => x.Id.Equals(request.Id));
  entity = _mapper.Map(request);

  _context.Update(entity);
  await _context.SaveChangesAsync(); // this update works

  succeeded = // some code
}
catch (Exception ex) 
{
  if (!succeeded)
  {
    // revert updating entity
    _mapper.Map(original, entity);
    _context.Update(entity);
    await _context.SaveChangesAsync(); // this update deletes
  }
}

Workaround

After seeing this issue PropertyValues.SetValues(obj) causes DELETE instead of UPDATE #16546, I tried using SetValues, and that does work.

So instead of

_mapper.Map(original, entity);
_context.Update(entity);

I used _context.Entry(entity).CurrentValues.SetValues(original);

Further technical details

EF Core version: 7.0.0 Database Provider: Npgsql.EntityFrameworkCore.PostgreSQL Operating system: Windows 10 IDE: Visual Studio 2022, Version17.4.1

MS699 avatar Jan 20 '23 13:01 MS699

This issue is lacking enough information for us to be able to fully understand what is happening. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

ajcvickers avatar Jan 24 '23 18:01 ajcvickers

EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.

BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

ajcvickers avatar Feb 08 '23 19:02 ajcvickers