开发者

Check for duplicates when saving

开发者 https://www.devze.com 2023-02-17 22:44 出处:网络
How to check for duplicates when savi开发者_运维技巧ng new object? Scenario: check for duplicates by some query -> when no duplicates perform saving

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消