简体   繁体   English

在不跨越多个上下文对象的情况下,Entity Framework 4中的TransactionScope是否有用途?

[英]Are there uses for TransactionScope in Entity Framework 4 in situations that do not span multiple context objects?

I am working on my first large project that uses EF4 and have been pondering concurrency situations as I am implementing certain business scenarios. 我正在做我的第一个使用EF4的大型项目,并且在实现某些业务场景时一直在考虑并发情况。 I understand that EF has built in support for optimistic concurrency by setting Concurrency Mode to Fixed on entity properties. 我了解EF通过将实体属性上的“并发模式”设置为“固定”来建立对开放式并发的支持。 This seems to be sufficient in most cases. 在大多数情况下,这似乎已足够。 Several things I am wondering about: 我想知道的几件事:

  1. In a situation where I first validate that an entity does not exist, then subsequently insert the entity. 在首先验证一个实体不存在的情况下,然后插入该实体。 Technically someone could have inserted that entity in the split second between my validation and my insert. 从技术上讲,有人可以在我的验证和插入之间的瞬间插入该实体。 What is the best practice to handle this scenario with EF? 用EF处理这种情况的最佳实践是什么? Naturally I am thinking about two possible solutions, pessimistic concurrency or handling a unique constraint exception that will occur. 自然,我在考虑两种可能的解决方案,悲观并发或处理将要发生的唯一约束异常。

  2. I am trying to remember if issuing a Begin Transaction/Commit Transaction block in SQL will automatically lock the tables involved, meaning it will force the pessimistic scenario I alluded to above. 我试图记住,如果在SQL中发出Begin Transaction / Commit Transaction块是否会自动锁定所涉及的表,这意味着它将迫使我在上文中提到过悲观的情况。 If so, will wrapping these two EF operations in TransactionScope achieve similar results? 如果是这样,将这两个EF操作包装到TransactionScope中是否会获得相似的结果?

  3. If TransactionScope will not force pessimistic concurrency, what will? 如果TransactionScope不会强制悲观并发,那会是什么?

  1. A DB constraint is the only reliable solution to this, because it's the only solution which can see uncommitted transactions from other writers. DB约束是唯一可靠的解决方案,因为它是唯一可以看到其他编写者未提交事务的解决方案。
  2. Don't presume that SQL Server is locking tables. 不要以为SQL Server会锁定表。 It might be locking rows. 它可能是锁定行。
  3. Lingering, uncommitted writes. 挥之不去,无懈可击。 Which are usually a bad idea with any data access technology. 对于任何数据访问技术而言,通常这都是一个坏主意。 Use constraints instead. 请改用约束。

Why would you want to use TransactionScope when not using multiple contexts? 不使用多个上下文时为什么要使用TransactionScope Well, maybe you need to get a server-generated key in the course of one transaction (think SCOPE_IDENTITY ). 好吧,也许您需要在一次事务过程中获得服务器生成的密钥(请考虑SCOPE_IDENTITY )。 In general, when you have multiple calls to SaveChanges() which must succeed or fail as a group. 通常,当您多次调用SaveChanges()必须成组成功或失败。

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

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