并发EF4 - 如何有条件地创建一个实体有条件、创建一个、实体

2023-09-06 06:36:30 作者:改变是痛苦,不改变是受苦

我需要能够创建一个新的用户实体的仅在所提供的电子邮件是独一无二的。

I need to be able to create a new User entity only if the provided email is unique.

我一直通过执行一个简单的如果说之前处理这个(!UserSet.Any(...))在我的 AddToUserSet(。 ..)。然而,这不是一个并发溶液和将重负载下断裂。

I've always handled this before by performing a simple if (!UserSet.Any(...)) before my AddToUserSet(...). However, this is not a concurrent solution and will break under heavy load.

我一直在寻找到交易,但AFAIK我需要设置上选择一个UPDLOCK过,但EF4并不支持这一点。

I've been looking into Transactions, but AFAIK I would need to set an UPDLOCK on the SELECT too, but EF4 does not support this.

如何其他人处理呢?

推荐答案

您可以强制通过包括在选择交易锁定:

You can force locking by including SELECT in transaction:

using (var scope = new TransactionScope())
{
    // Create context
    // Check non existing email
    // Insert user
    // Save changes
}

这将使用序列化交易这是你需要的,如果你想并发解决方案插入 - UPDLOCK是不够的,以确保新的记录您的交易过程中不添加

This will use serializable transaction which is what you need if you want concurrent solution for inserts - UPDLOCK is not enough to ensure that new record is not added during your transaction.

这可能是pretty的坏瓶颈,所以我同意@paolo:只需将唯一约束到数据库和catch异常插入过程中,如果电子邮件是不是唯一的

This can be pretty bad bottleneck so I agree with @paolo: simply place the unique constraint to the database and catch exception during insert if email is not unique.

从图书序列化的网上交易:

指定以下内容:

    Statements cannot read data that has been modified but not yet  
    committed by other transactions.

    No other transactions can modify data that has been read by the  
    current transaction until the current transaction completes.

    Other transactions cannot insert new rows with key values that
    would fall in the range of keys read by any statements in the current
    transaction until the current transaction completes.

     

范围锁放置于匹配的关键值的范围   每个语句搜索条件   在一个事务中执行。此块   从更新其他交易或   插入任何行,将有资格   任何被执行的语句   当前事务。意即   如果任何一个的发言   事务被执行的第二   时间,他们将读取同一组   行。范围锁一直持有到   交易完成。这是   最严格的隔离   水平,因为它锁定整个范围   键以及持有这些锁,直到   交易完成。因为   并发性是较低的,使用此选项   仅在必要时。此选项   相同的效果上设置HOLDLOCK   在所有SELECT语句中的所有表   一个事务。

Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. This blocks other transactions from updating or inserting any rows that would qualify for any of the statements executed by the current transaction. This means that if any of the statements in a transaction are executed a second time, they will read the same set of rows. The range locks are held until the transaction completes. This is the most restrictive of the isolation levels because it locks entire ranges of keys and holds the locks until the transaction completes. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.