开发者

Concurrency in EF4 - How to conditionally create an entity

I need to be able to create a new User entity only if the pr开发者_运维问答ovided email is unique.

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.

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.

How does everyone else handle 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
}

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.

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.

Serializable transaction from Books online:

Specifies the following:

    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.

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.


in addition to your check, you could add a unique constraint on the email field directly on the DB

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜