【问题标题】:Entity Framework errors when calling an ASP.NET hosted WCF Service concurrently同时调用 ASP.NET 托管的 WCF 服务时出现实体框架错误
【发布时间】:2012-08-22 11:45:05
【问题描述】:

我有一个简单的 ASP.NET 托管 WCF 服务,它有几个方法,在使用实体框架时都具有相同的模式...

public void Operation1(string username)
{
    using(MyEFContext context = new MyEFContext())
    {
        UserInfo info = (from ui in context.UserInfos
                         where ui.User.Equals(username)
                         select ui).FirstOrDefault<UserInfo >();

        info.LastAccess = DateTime.Now;

        // Operation specific code, such as getting information using the EF context

        context.SaveChanges();
    }
}

这是一个简化版本以保持示例简单,但即使是这个简单版本也与我的生产代码集存在相同的错误。该代码首先使用实体​​框架获取用户信息,更新用户 LastAccess 字段,然后执行特定于操作的代码。特定于操作的代码只是查询信息。最后,它调用 SaveChanges,以便将 LastAccess 保存回数据库。现在这一切都运行良好,直到我的客户同时进行两个调用。

客户端进行了两次调用,每次调用不同的操作,但它们都具有与上面所示相同的代码模式。有时两个电话都成功完成。但有时其中一个会产生错误,它可能是以下三个中的任何一个......

System.Data.EntityException: The underlying provider failed on Open. ---> 
System.InvalidOperationException: The connection was not closed. The connection^s current 
state is connecting.

System.Data.EntityCommandExecutionException: An error occurred while executing the command
definition. See the inner exception for details. ---> System.InvalidOperationException: 
ExecuteReader requires an open and available Connection. The connection^s current state is 
closed.

System.InvalidOperationException: Invalid attempt to read when no data is present.

显然我对 EF 和 ASP.NET 的理解是有缺陷的,因为我希望这两个操作甚至可以并行工作。我是否需要锁定每种方法,以便它们一次只发生一个?肯定不是。有什么想法吗?

【问题讨论】:

  • 您是否使用 Per Call 服务激活,这意味着对 WCF 服务的每次调用都会导致创建一个单独的服务实例吗?
  • Per-Call 的默认设置。
  • 看看这个问题,他们指出了在 IIS 中托管时使用集成安全性的问题。您是否在默认应用程序池中托管此应用程序?:stackoverflow.com/questions/2475008/…
  • 在这里找到答案stackoverflow.com/questions/2575485/…。事实证明,为我的所有上下文重用相同的 EntityConnection 实例是问题所在。所以现在我每次都创建一个新的。

标签: c# asp.net multithreading entity-framework exception


【解决方案1】:

在这里找到答案Managing EntityConnection lifetime。事实证明,为我的所有上下文重用相同的 EntityConnection 实例是问题所在。所以现在我每次都创建一个新的。

【讨论】:

    猜你喜欢
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2016-09-05
    • 2019-01-31
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多