Long running Entity Framework transaction

谁说我不能喝 提交于 2020-01-03 15:38:53

问题


when 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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6180466/long-running-entity-framework-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!