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

前端 未结 4 1121
夕颜
夕颜 2020-12-08 14:16

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

相关标签:
4条回答
  • 2020-12-08 14:24

    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.

    0 讨论(0)
  • 2020-12-08 14:32

    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

    0 讨论(0)
  • 2020-12-08 14:47

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

    db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql, parameters);
    
    0 讨论(0)
  • 2020-12-08 14:50

    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;
         }
    }
    
    0 讨论(0)
提交回复
热议问题