Avoiding Database Update Concurrency

Today we’re seeing how can we avoid database concurrency while saving records in the database.
As we could see in the previous articles:
1. CRUD Pattern – Alert nr. 1 – I’ve shown you a way to avoid changing fields that are supposed to be immutable;
2. Validation is Golden Rule – I’ve enforced an idea that you should validate action inputs before executing logic;
3. The importance of Trim() – I’ve shown you a way to avoid saving unwanted space characters into database;
but our CreateOrUpdate action is not properly handling concurrency yet.
How can concurrency happen?
Consider a simple example where User-A and User-B open the same record at the same time. They would load the same version of the record that was retrieved from database.
Now User-A edits the record and saves it. In this case, User-B continues to see the old data.
Now User-B edits the record and saves it. In this case, User-B would override the save made by User-A.
This is true if we don’t handle concurrent requests.
How can we avoid concurrency while saving data into database?
It’s actually simple. If your entities already have the LastUpdatedOn field that contains the DateTime of the entity’s last update you just need to guarantee that when you’re updating the entity, the LastUpdatedOn fields match:

Remember, concurrency will ALWAYS exist!
Tiago