ObjectContext.Connection.BeginTransaction() 是否使用 MSDTC?
我想确认实体框架的ObjectContext.Connection.BeginTransaction()方法返回的事务是否使用MSDTC(微软分布式事务协调器)的支持?
有没有办法在不支持MSDTC的情况下使用事务?
I want confirm if the Transaction that Entity Framework's ObjectContext.Connection.BeginTransaction() method returns uses the support of MSDTC (Microsoft Distributed Transaction Coordinator) or not?
Is there any way to use transactions without support of MSDTC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在一定条件下,它会自动升级为由 MSDTC 协调的交易。每次调用
ObjectContext.SaveChanges()
时,如果范围内尚无事务,则会创建一个新事务(如果范围内已存在活动事务,则它将登记在该事务中)。但是,默认情况下,每次调用ObjectContext.SaveChanges()
时,连接也会打开和关闭。因此,如果您在方法开头调用ObjectContext.Connection.BeginTransaction()
,然后在保留原始事务的同时多次调用ObjectContext.SaveChanges()
,对于某些版本的 SQL Server 和实体框架,这可能会导致事务升级为 MSDTC,因为它现在在单个事务中使用不同的连接。如果您想避免事务升级为 MSDTC,请在开始时显式打开连接并在完成后关闭它:但是,建议您使用 TransactionScope,因为它更灵活,对平台的依赖性较小,如果将来您决定确实需要需要 MSDTC 的东西,这将使您更轻松。如果存在活动的 TransactionScope,EntityFramework 将自动加入事务:
It will automatically promote to a transaction coordinated by MSDTC under certain conditions. Each time you call
ObjectContext.SaveChanges()
a new transaction is created if there isn't already one in scope (if there is already an active transaction in scope, it will enlist in that transaction). However, by default, the connection will also be opened and closed each time you callObjectContext.SaveChanges()
. So if you're callingObjectContext.Connection.BeginTransaction()
at the beginning of a method, then callingObjectContext.SaveChanges()
multiple times while holding onto the original transaction, with some versions of SQL Server and Entity Framework, this can cause the transaction to get promoted to MSDTC because it's now using different connections within a single transaction. If you're trying to avoid your transaction getting promoted to MSDTC, then explicitly open your connection at the beginning and close it when you're done:However, it's recommended that you use a TransactionScope, as it's more flexible, less platform-dependent, and will make it easier on you if in the future you decide you do actually need to something that requires MSDTC. EntityFramework will automatically enlist in the transaction if there's an active TransactionScope: