Entity framework: InvalidOperationException: Invalid operation. Connection closed

I use Entity Framework to execute stored procedures (Azure SQL Server) in my database.

My C # code is as follows:

using (var context = new MyDataContext())
    numberOfEffectedRows = context.MySPName(this.Id);

In most cases (99.9%) of performances this works fine. But sometimes this error did not work:

System.InvalidOperationException: Invalid operation. The connection is closed.
   at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
   at System.Data.SqlClient.SqlInternalTransaction.Rollback()
   at System.Data.SqlClient.SqlInternalTransaction.Dispose(Boolean disposing)
   at System.Data.SqlClient.SqlTransaction.Dispose(Boolean disposing)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Dispose(DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.EntityTransaction.Dispose(Boolean disposing)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass4b.<ExecuteFunction>b__49()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteFunction(String functionName, ObjectParameter[] parameters)
   at ***.MyDataContext.MySPName(Nullable`1 Id) in ***
   at ***.DoSomething() in ***

When does this happen:

  • I do not know why this is happening. It seems to me randomized.
  • I do not know if my "MySPName" was executed or not.

Does anyone know why this is happening, and how can I find out if my stored procedure is running or not?

+4
source share
3 answers

- , Connect Timeout

 connectionString="Data Source=..;Initial Catalog=;Persist Security Info=..;User ID=..;Password=..;Connect Timeout=.."

SQL Server Profiler

+1

Linq . numberOfEffectedRows. "" , , . numberOfEffectedRows , , .

0

EntityFramework , , - .

- .

, , , .

https://msdn.microsoft.com/en-us/library/microsoft.practices.unity.perrequestlifetimemanager(v=pandp.30).aspx

what you can do is

container.RegisterType<IDataContext, MyDataContext>(new PerRequestLifetimeManager()); 

and then you insert the DataContext wherever you need to access it.

so that the context closes automatically when the container is located

0
source

Source: https://habr.com/ru/post/1623126/


All Articles