0
votes

I have a repository using EF 4.1 and DbContext when updating an object I receive this error

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

I suppose is connected with optimistic concurrency updates.. Any idea how to solve it?

  public void UpdateAddingCandidate(Event eventObj, int candidateId)
    {
        Candidate newCandidate = db.Candidates.AsNoTracking().FirstOrDefault(x => x.CandidateId == candidateId);
        eventObj.Candidate = newCandidate;
        eventObj.CandidateId = newCandidate.CandidateId;
        db.Entry(eventObj).State = EntityState.Modified;
    }
1

1 Answers

0
votes

Look into ObjectContext.Refresh, which allows you to refresh entities from the database. You can set the RefreshMode to ClientWins or StoreWins.

Use Try...Catch logic and handle the conflict in the catch to force the change with ClientWins or pull down the changed data into the context and restart the edit. In most cases, the latter is the better approach.