C# TransactionScope - L2E
是否值得在 Linq to Entities 上使用 System.Transactions.TransactionScope?
在 MS 文档上,它说 SQL 在 ObjectContext.SaveChanges 中调用() 全部在内部汇总为一个事务。
我们有 1 个数据库连接,即文件系统上的本地 SQLite 数据库。我们只是想确保对数据库的所有操作都是原子的,我们需要 TransactionScope 吗? 当我们调用某些删除、更新、插入等操作时,我们希望它们全部发生或根本不发生。
Is it worth using System.Transactions.TransactionScope on Linq to Entities?
On the MS documentation, it says that SQL calls within ObjectContext.SaveChanges() are all rolled into one transaction internally.
We have 1 database connection, that is a local SQLite database on the file system. We just want to make sure all our operations to the database are atomic, do we need TransactionScope?
I.E. when we call for some deletes, updates, inserts, etc., we want them all to happen or none at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
乔恩,不,您不需要使用 TransactionScope。乐观并发由 Linq 自动处理。您提供的链接中的代码示例很好地解释了您不必自己回滚事务。我将使用与示例中相同的代码:
注意刷新、重新保存,这可以解决您的问题。您可以通过从 try 块中抛出异常来测试这一点。
此致
Jon, no you don't need to use TransactionScope. Optimistic concurrency is handled automatically by Linq. The code sample in the link you provide explains that rather well, you don't have to roll back transactions yourself. I would use the same code as in the sample:
Notice the refresh, re-save, which handles your concern. You could test this out by throwing an exception from within the try block.
Best Regards
如果您想在单个事务中包含
ObjectContext.SaveChanges
以外的内容(例如读取要更改的数据以及更改),那么您需要使用TransactionScope
。If you want to include more than the
ObjectContext.SaveChanges
in a single transaction (e.g. reads of data you are going to change, as well as the changes) then you need to make use ofTransactionScope
.如果您需要执行理查德所说的操作(尽管看起来不太可能),您可以使用以下代码:
You could use the following code if you need to do what Richard says (though it seems rather unlikely):