开发者

Long running Entity Framework transaction

开发者 https://www.devze.com 2023-03-09 14:31 出处:网络
w开发者_StackOverflowhen user opens edit form for some entity, I would like to LOCK this entity and let her make any changes. During editing she needs to be sure that nobody else does any edit operati

w开发者_StackOverflowhen user opens edit form for some entity, I would like to LOCK this entity and let her make any changes. During editing she needs to be sure that nobody else does any edit operations on it.

How can I lock an entity in Entity Framework (C#) 4+, database MS SQL Server 2008?

Thank you so much in advance!


Bad idea, especially if you have many concurrent users. You will be killing scalability if you lock the rows in the database.

It is better to detect whether others have made edits and if so, inform the user and let them decide what to do.

The timestamp/rowversion data type is a good choice for a field to find out if any changes were made to a row data.


There are two ways to handle these situations:

  • Optimistic concurrency where you allow concurrent edits and inserts and catch exception if something violates concurrency rules. Optimistic concurrency is enforced by unique constraints guarding inserts of the same items and by timestamps / row version columns guarding concurrent updates to the same item. If somebody else updates row when current user is making changes the application will throw OptimisticConcurrencyException during saving and you will have to allow user to either overwrite other changes or reload new stored data.

  • Pessimistic concurrency where the record is locked for the duration of the operation executed by any client preventing other clients to update the same record. Pessimistic concurrency is usually enforced by custom columns added to your tables like LockedBy, LockedAt, etc. Once these columns are filled nobody else can select the record for edit. LockedAt can help you implement some automatic expiration of issued locks. Long running "EF transactions" are not long running database transactions.

Your initial description leads to second scenario which makes sense in some applications.

0

精彩评论

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