EF6 将每个存储过程调用包装在其自己的事务中.如何防止这种情况?

使用 SQL Server Profiler 进行分析:EF 6 使用 BEGIN TRANCOMMIT TRAN 包装每个存储过程调用.

Profiled with SQL Server Profiler: EF 6 wraps every single stored procedure call with BEGIN TRAN and COMMIT TRAN.

这不是一个突破性的改变吗?

Is not it a breaking change?

也许这不仅是一个重大变化,而且使 SP 中的任何事务逻辑都不可能,因为我们永远可以使用 ROLLBACK TRAN 在存储过程中回滚我们的事务(注意: SQL Server 中没有嵌套事务),因此一次回滚将回滚到 @@TRANCOUNT 零.因为我们在事务中,因为 EF 6 我们得到执行后的事务计数表明 BEGIN 和 COMMIT 语句的数量不匹配.先前计数 = 1,当前计数 = 0."标准 SQL Server 错误.

Maybe it is not only a breaking change, but makes any transactional logic impossible in SPs as we never can rollback our transaction in the stored procedure using ROLLBACK TRAN (note: there are no nested transactions in SQL Server), so one rollback rollbacks to @@TRANCOUNT zero. As we were in a transaction because EF 6 we got "Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0." standard SQL Server error.

请不要问我为什么要调用存储过程.我有数百个,它们都在使用 TRY ... COMMIT ... CATCH ROLLBACK 逻辑.

Please do not ask me why I want to call stored procedures. I have hundreds, and all of them are using TRY ... COMMIT ... CATCH ROLLBACK logic.

有什么想法可以防止 EF 6 这样做吗?

Any ideas how can I prevent EF 6 to do this?

推荐答案

ExecuteSqlCommand 方法的重载可以防止这种行为:

There is an overload of the ExecuteSqlCommand method that prevents this behavior:

db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql, parameters);

相关文章