Database.BeginTransaction 与 Transactions.TransactionScope [英] Database.BeginTransaction vs Transactions.TransactionScope
问题描述
System.Transactions.TransactionScope
和 EF6 的 Database.BeginTransaction
有什么区别?
What is the difference between System.Transactions.TransactionScope
and EF6's Database.BeginTransaction
?
有人可以举一个小例子,或者只是解释当有明显区别时使用哪个?
Could someone give a small example or just explain which one to use when with a clear difference?
P.S:在我的项目中,我使用的是 EF6.我已经阅读了文档,但没有太大帮助.还查找了示例,但他们更喜欢使用 SqlConnection.BeginTransaction
,现在 MS 在 EF6 中引入了这个新的 Database.BeginTransaction
.
P.S: In my project, I'm using EF6. I've already read the documentation but it didn't help much. Also looked up the examples but they are rather using SqlConnection.BeginTransaction
and now MS has introduced this new Database.BeginTransaction
in EF6.
推荐答案
我在 Entity Framework 6 的文档中找到了答案:
I found out the answer in Entity Framework 6's documentation:
随着 EF6 的引入,Microsoft 建议使用新的 API 方法:Database.BeginTransaction()
和 Database.UseTransaction()
.尽管 System.Transactions.TransactionScope
仍然受到很好的支持,但对于大多数 EF6 用户来说,它不再必需.
With the introduction of EF6, Microsoft recommends to use new API methods: Database.BeginTransaction()
and Database.UseTransaction()
. Although System.Transactions.TransactionScope
is still very well supported, it is no longer necessary for most users of EF6.
虽然 Database.BeginTransaction()
仅用于与数据库相关的操作事务,System.Transactions.TransactionScope
除此之外,还使普通 C#"成为可能代码"也是事务性的.
While Database.BeginTransaction()
is used only for database related operations transaction, System.Transactions.TransactionScope
, in addition to that, makes it possible for 'plain C# code' to also be transactional.
因此,使用 Database.BeginTransaction()
在 EF6 的事务中只执行与数据库相关的操作,否则使用 System.Transactions.TransactionScope
混合数据库操作和 C#在一个事务中一起编码.
Hence, use Database.BeginTransaction()
where ever doing only db related operations in a transaction in EF6 otherwise use System.Transactions.TransactionScope
for mixing db operations and C# code together in a transaction.
对于那些仍然喜欢 TransactionScope
方法的人,建议他们检查其局限性,尤其是在云场景中(云场景不支持分布式事务).
For those who still prefer the TransactionScope
approach, it is recommended they checkout its limitations, especially in cloud scenarios (cloud scenarios do not support distributed transactions).
可以在此处
这篇关于Database.BeginTransaction 与 Transactions.TransactionScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!