0

I have .net core api that uses NHibernate, session is per request, when request start session is open at the end of the request session is committed in transaction.

One of the tables is being used as cache table so rows should be deleted in some cases.

One case is when getting data from another api crossing results with data in the table in order to take the newest rows according to date updated field, each older row is being deleted as part of this process. Another case is a background service that gets events in order to indicate that the record is older and need to be deleted.

The issue is that in the same time when deleting older rows other request can actually update this row with new values.

Of curse that this scenario cause an exception:

NHibernate.StaleObjectStateException: 'Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

What is the best way to solve this situation and detect that row has been deleted before SaveOrUpdate from another request at the same time?

Thank you

user3132295
  • 288
  • 4
  • 23
  • Catch the exception and do nothing, the entry is not there so what else should be done with the updated values? – Firo Dec 09 '22 at 08:10
  • Thank you for your response, in this case I want to try to save it as new item in the table and not the one that already in the nhibernate session – user3132295 Dec 12 '22 at 09:46
  • 1
    Thats what `session.Merge()` is for. It checks if the row is present and updates it or inserts a new one. There is still the small race condition: when it is deleted between checking and updating. I solved a similar situation with a loop which checks for StaleObjectStateException and repeats x times before escalating the exception. – Firo Dec 12 '22 at 16:01
  • Thank you I tried to use merge but still sometimes got an error, so I will try the x times you suggested – user3132295 Dec 12 '22 at 18:15
  • I tried the merge again and still get StaleObjectStateException. I deleted the row from DB before calling merge and got this exception, what am I missing? Thank you – user3132295 Dec 12 '22 at 20:15
  • Found I had Get(id) so I had to Evict the entity before the Merge – user3132295 Dec 12 '22 at 21:59

0 Answers0