Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF6 wraps every single stored procedure call in its own transaction. How to prevent this?

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?

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.

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.

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

like image 350
g.pickardou Avatar asked Nov 15 '13 01:11

g.pickardou


People also ask

What is wrapper stored procedure?

Usually, stored procedures are wrapped into methods of database access classes. The wrapping work must be done by a programmer and it is very boring. My idea is to automatically generate wrappers for stored procedures based on strongly typed interface definition and some metadata fetched from the DBMS.

Can a stored procedure call itself?

A stored procedure can call itself up to the maximum nesting level of 32. This is referred to as recursion.

Why do stored procedures need to be recompiled?

If a database undergoes significant changes to its data or structure, recompiling a procedure updates and optimizes the procedure's query plan for those changes. This can improve the procedure's processing performance.

What is Return_value stored procedure?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.


2 Answers

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

db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql, parameters); 
like image 189
Massimo Zerbini Avatar answered Oct 23 '22 14:10

Massimo Zerbini


In EF 6.1.2, a flag controls the behavior. Setting EnsureTransactionsForFunctionsAndCommands to false will affect SPs that have been imported into an entity (these call ExecuteFunction() internally).

 using (SomeEf6Context ctx = NewContext())  {      ctx.Configuration.EnsureTransactionsForFunctionsAndCommands = false;      // Call an imported SP  }       

The setting will not affect any SaveChanges() calls.

MSDN Link

like image 22
crokusek Avatar answered Oct 23 '22 14:10

crokusek