0

So I am receiving userdata from a form where they can adjust their data I don't know if anything got changed so I want to port the data to the model linked with the database and update it. However if they just pressed "save" but not change anything my database will give the error:

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s).

My code

public int relatie_update(relatieBeheer rel)
    {
        var db = new DataContext(_configuration);

        relData relatie = this.relatie_get(rel.id_rel); //I get the existing rel from database
        relatie.update(rel); //this is where I port my relatiebeheer -> reldata
        db.relatie.Update(relatie);

        db.SaveChanges();

        return rel.id_rel;
    }

Is there a clean way to solve this problem? or do I need to check manually whether my relData has changed and have a conditional update() call?

  • Try to remove `db.relatie.Update(relatie);` EF Core tracks object changed properties automatically. – Svyatoslav Danyliv Jul 01 '22 at 13:30
  • FWIW, as a side note, I'd probably put a `using()` around the `new DbContext()`, see also https://stackoverflow.com/questions/16162384/use-of-the-using-and-dbcontext – Stefan Wuebbe Jul 01 '22 at 14:13

0 Answers0