Profiled with SQL Server Profiler: EF 6 wraps every single stored procedure call with BEGIN TRAN
and COMMIT TRAN
.
Is not it a breaking cha
Just to contribute, I'm using Unity as DI, EF 6.1.3 and database first and I was getting the message: "New transaction is not allowed because there are other threads running in the session" when I called a procedure or a function mapped in my edmx file. The option EnsureTransactionsForFunctionsAndCommands = false fixed the problem. The Max Zerbini's solution worked too, but I would've to use that way for each procedure call.
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
There is an overload of the ExecuteSqlCommand
method that prevents this behavior:
db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql, parameters);
As what crokusek said, you can set that flag to disable transactions for SPs.
If you are using any Dependency Injection (DI) library, you can set that like this(I am using Simple Injector):
public partial class Startup
{
public Container ConfigureSimpleInjector(IAppBuilder app)
{
var container = new Container();
// Configure OWIN and Identity Framework
...
// Configure persistence
container.RegisterPerWebRequest<FakeDbContext>(() =>
{
var fakeDbContext = new FakeDbContext();
fakeDbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
return fakeDbContext;
}
// Register other services
...
container.Verify();
// For MVC
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
return container;
}
}