【问题标题】:Database timeout when perfoming first update operation in ADO.NET Entity Framework在 ADO.NET Entity Framework 中执行第一次更新操作时数据库超时
【发布时间】:2011-11-24 06:35:21
【问题描述】:

我们正在使用 WCF 服务创建一个应用程序,该服务使用实体框架访问数据库。我们正在使用 SQL Server 2005、.Net 4.0、Entity Framework 4.0 和 C#。当部署 WCF 服务并启动应用程序时,首先数据库操作始终是SELECT 以读取一些数据,然后,在用户与应用程序交互时,可能会发生一些数据库更新。观察到的问题是部署服务后执行的第一个数据库UPDATE 操作,通常会失败并显示错误:

An error occurred while updating the entries.
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

SaveChanges() 方法中会出现此错误,通常此方法包含在如下事务中:

// TransactionScopeOption.RequiresNew, IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(1)
using (TransactionScope scope = TransactionScopeUtil.CreateTransactionScope())
{
  using (var dbcontext = new DBCtx("connectionstring"))
  {
    dbcontext.Connection.Open();

    // Read and update database.

    dbcontext.SaveChanges();

    dbcontext.Connection.Close();
  }
}
scope.Complete();

第一次数据库更新操作通常会失败,然后在重新部署服务之前永远不会再次失败。

会不会是冷启动时的数据库连接池有问题?

我们对增加连接/命令超时的解决方案/变通办法感到不满意,因为这可能会掩盖未来的性能问题,并且数据库更新通常不是“大”。

【问题讨论】:

  • 是第一次更新还是第一次访问数据库?此外,您的错误似乎不是来自事务,而是来自对服务的调用。
  • 是第一次数据库更新,因为客户端应用程序在启动时调用服务,检索一些数据以填充列表,组合......并且用户可以更新数据库中的信息,引发此错误第一次。

标签: c# .net sql-server entity-framework-4 ado.net


【解决方案1】:

尝试使用TransactionManager.MaximumTimeout 可能你已经使用this。 所以如果不是问题,那么以下内容:

EF desinger 连接作为“默认命令超时”存在,因此使用 dbcontext 将命令超时设置为某个值。 它将为上下文命令设置底层命令超时。

context.CommandTimeout = 180;

查看此堆栈溢出question 了解更多详情

您应该在using 语句中使用scope.Complete(); - MSDN - Transaction Scope implementation

using(TransactionScope scope = new TransactionScope())
     {
          /* Perform transactional work here */
          scope.Complete();
     }

【讨论】:

  • 由于这不容易重现,我将上下文命令超时更改为 1 分钟,并将事务超时设置为当前的 1 分钟,并将尝试。希望会奏效:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多