实体框架:InvalidOperationException:无效的操作。连接已关闭

时间:2016-01-06 15:52:59

标签: c# entity-framework

我使用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 ***

发生这种情况时:

  1. 我不知道为什么会这样。在我看来,这似乎是随机的。
  2. 我不知道我的“MySPName”是否被执行了。
  3. 有人知道为什么会这样,以及我如何知道我的存储过程是否被执行?

3 个答案:

答案 0 :(得分:1)

连接已关闭是由于超时,因此建议您检查连接字符串中的Connect Timeout

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

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

答案 1 :(得分:0)

Linq查询被懒惰地评估。查询将在您第一次访问numberOfEffectedRows时运行。因为你使用&#34;使用&#34;围绕数据上下文的创建,它一旦处理掉范围就被处理掉。如果您访问使用范围之外的numberOfEffectedRows,则会发生这种情况,因为查询无法在没有有效数据上下文的情况下运行。

答案 2 :(得分:0)

EntityFramework上下文不是线程安全的,由于某些奇怪的原因,有可能在执行期间关闭数据上下文。

处理这种惊喜的一种方法是为每个请求设置一个上下文。

这是最简单的解决方案,因此您“希望”再也不会遇到此异常。

点击这里

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

你可以做的是

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

然后将DataContext注入您需要访问它的任何位置。

这样做,当容器被处理时,上下文将自动关闭

相关问题