长时间运行的实体框架事务
当用户打开某个实体的编辑表单时,我想锁定该实体并让她进行任何更改。在编辑过程中,她需要确保没有其他人对其进行任何编辑操作。
如何锁定实体框架 (C#) 4+、数据库 MS SQL Server 2008 中的实体?
提前非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
坏主意,特别是如果您有很多并发用户。如果锁定数据库中的行,就会破坏可伸缩性。
最好检测其他人是否进行了编辑,如果是,则通知用户并让他们决定要做什么。
时间戳
/rowversion< /code> 数据类型是字段查找行数据是否发生任何更改的不错选择。
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.有两种方法可以处理这些情况:
乐观并发,允许并发编辑和插入,并在某些内容违反并发规则时捕获异常。乐观并发是通过保护相同项目插入的唯一约束和保护对同一项目的并发更新的时间戳/行版本列来强制执行的。如果其他人在当前用户进行更改时更新行,则应用程序将在保存期间抛出 OptimisticConcurrencyException ,并且您必须允许用户覆盖其他更改或重新加载新存储的数据。
悲观并发,其中记录在任何客户端执行操作期间被锁定,以防止其他客户端更新同一记录。悲观并发通常是通过添加到表中的自定义列(例如
LockedBy
、LockedAt
等)来强制执行的。一旦这些列被填充,其他人就无法选择要编辑的记录。LockedAt
可以帮助你实现一些已发出的锁的自动过期功能。长时间运行的“EF 事务”不是长时间运行的数据库事务。您最初的描述导致了第二种情况,这在某些应用程序中是有意义的。
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.