简体   繁体   English

长时间运行的实体框架事务

[英]Long running Entity Framework transaction

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?如何在 Entity Framework (C#) 4+、数据库 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. timestamp / rowversion数据类型是一个不错的选择,可以让字段查明是否对行数据进行了任何更改。

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.如果其他人在当前用户进行更改时更新行,应用程序将在保存期间抛出OptimisticConcurrencyException ,您将不得不允许用户覆盖其他更改或重新加载新存储的数据。

  • 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.悲观并发通常由添加到表中的自定义列(如LockedByLockedAt等)强制执行。一旦这些列被填充,其他人就无法 select 记录进行编辑。 LockedAt can help you implement some automatic expiration of issued locks. LockedAt可以帮助您实现一些自动过期已发布的锁。 Long running "EF transactions" are not long running database transactions.长时间运行的“EF 事务”不是长时间运行的数据库事务。

Your initial description leads to second scenario which makes sense in some applications.您最初的描述导致第二种情况,这在某些应用程序中是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM