How to check for duplicates when savi开发者_运维技巧ng new object?
Scenario:
- check for duplicates by some query -> when no duplicates perform saving
Is not good because between check and save there is plenty of time when other user can insert new object with the same data (high activity of users).
Should I check for exception when saving or what?
using (var tx = session.BeginTransaction(IsolationLevel.Serializable))
{
bool alreadyExists = session.Query<MyEntity>()
.Any(x => x.UniqueProp = newEntity.UniqueProp);
if (!alreadyExists)
session.Save(newEntity)
tx.Commit();
}
The Serializable
isolation level guarantees nobody can insert a matching row between the query and the insert. Of course the downside is reduced concurrency because of the range locks.
Handling the exception is an alternative.
精彩评论