c# – 实体框架:InvalidOperationException:无效的操作.连接已关闭

我使用Entity Framework在我的数据库中执行存储过程(Azure SQL Server).

我的C#代码如下所示:

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

在大多数情况下(99.9%)执行,这很好.但是,有时它会因此错误而失败:

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 ***

发生这种情况时:

>我不知道为什么会这样.在我看来,这似乎是随机的.
>我不知道我的“MySPName”是否被执行了.

有人知道为什么会这样,以及我怎么知道我的存储过程是否被执行?

最佳答案 连接已关闭是由于超时,因此建议您检查连接字符串中的连接超时

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

对于诊断,我建议您运行SQL Server Profiler

点赞