C# EF Code First - 超时已过期。在完成之前超时时间已过

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19917167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:06:51  来源:igfitidea点击:

EF Code First - Timeout expired. The timeout period elapsed prior to completion

c#sql-serverentity-frameworkef-migrations

提问by Chi Chan

Apology for this strangely worded question. I don't know what the actual problem is but hopefully someone can give me some insights.

为这个措辞奇怪的问题道歉。我不知道实际问题是什么,但希望有人能给我一些见解。

I am getting the following error when trying to run migrations:

尝试运行迁移时出现以下错误:

Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

It is interesting to note that on my laptop this is not happening but on my VM (azure - large) this is happening with 100% failure rate.

有趣的是,在我的笔记本电脑上没有发生这种情况,但在我的 VM(天蓝色 - 大)上发生这种情况的故障率为 100%。

I am using Ef 6.0.0 -rc1. Please note, updating EF is not an option. If updating to EF 6.0.0 or 6.0.1 I will get the following error with 100% failure rate:

我正在使用Ef 6.0.0 -rc1。请注意,更新 EF 不是一种选择。如果更新到 EF 6.0.0 或 6.0.1,我将收到以下错误,失败率为 100%:

Errors during Code First add-migration

Code First 添加迁移期间的错误

I have also timed the error. It takes about 1.5 min to trigger the error. When running with -Verboseflag it was trying to create 200 tables with indexes. Copying the sql query and excuting it in SSMS takes 5 secs.

我也对错误进行了计时。触发错误大约需要 1.5 分钟。使用-Verbose标志运行时,它试图创建 200 个带索引的表。复制 sql 查询并在 SSMS 中执行它需要 5 秒。

A few things that I have tired but didn't work:

我已经累了但没有工作的一些事情:

1) Setting ObjectContext.CommandTimeout = 36000 // 10 hours!as indicated here:

1)设置ObjectContext.CommandTimeout = 36000 // 10 hours!如下所示:

https://stackoverflow.com/a/6234593/305469

https://stackoverflow.com/a/6234593/305469

2) Setting timeout in connection string in "web.config":

2)在“web.config”中的连接字符串中设置超时:

connectionString="Data Source=localhost;Initial Catalog=myDB;Integrated Security=SSPI;Connection Timeout=36000"

connectionString="Data Source=localhost;Initial Catalog=myDB;Integrated Security=SSPI;Connection Timeout=36000"

3) Setting "machine.config" transaction maxTimeout:

3)设置“machine.config”事务maxTimeout:

<system.transactions> <machineSettings maxTimeout="00:00:00" /> </system.transactions>

<system.transactions> <machineSettings maxTimeout="00:00:00" /> </system.transactions>

4) Setting "remote query timeout" on sql server

4)在sql server上设置“远程查询超时”

USE MyDB;
GO
EXEC sp_configure 'remote query timeout', 0 ;
GO
RECONFIGURE ;
GO

So what is happening? How come CommandTimeoutis not being respected? Any suggestions?

那么发生了什么?怎么CommandTimeout不被尊重?有什么建议?

Full trace as follows:

完整跟踪如下:

System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass32.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:8cbbc70c-8182-417e-9aca-4603f797340d
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

回答by GrokSrc

I ran into this in my production environment because it was producing queries like the ones here: Why does Entity Framework 6 generate complex SQL queries for simple lookups?

我在我的生产环境中遇到了这个问题,因为它正在生成类似于这里的查询:为什么 Entity Framework 6 为简单的查找生成复杂的 SQL 查询?

This is actually related to a bug in this version of EF: https://entityframework.codeplex.com/workitem/2083

这实际上与此版本 EF 中的一个错误有关:https: //entityframework.codeplex.com/workitem/2083

They changed the default null semantics from 5 to 6 so I'm guessing you had the same problem I did after upgrading. My machine had a fraction of the data as my remote installation and until I got to production I didn't know I had a performance issue. The queries will often produce a table scan which will time out for larger tables.

他们将默认的空语义从 5 更改为 6,因此我猜您在升级后遇到了同样的问题。我的机器有一小部分数据作为我的远程安装,在我投入生产之前,我不知道我遇到了性能问题。查询通常会产生表扫描,这对于较大的表会超时。

To change it back so that it works like EF5 you have to set:

要将其改回以使其像 EF5 一样工作,您必须设置:

DbContextConfiguration.UseDatabaseNullSemantics = true

DbContextConfiguration.UseDatabaseNullSemantics = true

See here: http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.usedatabasenullsemantics(v=vs.113).aspx

请参阅此处:http: //msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.usedatabasenullsemantics(v=vs.113).aspx

The bug was fixed in EF 6.1 but you still have to set the option above to get simple where conditions.

该错误已在 EF 6.1 中修复,但您仍然必须设置上面的选项以获得简单的 where 条件。

回答by Craig Strohl

I just had the same exact issue, i know this thread is a year old but maybe it will help someone else.

我刚刚遇到了同样的问题,我知道这个线程已经有一年了,但也许它会帮助其他人。

I was trying to create the database in entity 5 using the Package Manager Console using the connection string below.

我试图使用包管理器控制台使用下面的连接字符串在实体 5 中创建数据库。

update-database -ConfigurationTypeName My.Project.EF.Migrations.Configuration -ConnectionStringName MyDatabaseDev -ProjectName Project.Name -StartUpProjectName Database.Name

更新数据库 -ConfigurationTypeName My.Project.EF.Migrations.Configuration -ConnectionStringName MyDatabaseDev -ProjectName Project.Name -StartUpProjectName Database.Name

Each time i ran it i got the error below.

每次我运行它时,我都会收到以下错误。

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

超时已过。操作完成前超时时间已过或服务器未响应。

To fix it i simply added the -forceparameter and it went right through.

为了修复它,我简单地添加了-force参数,它就通过了。

回答by Stephan

In the constructor of Configuration.cs class (in migration Folder) add the property CommandTimeout = Int32.MaxValue;

在 Configuration.cs 类的构造函数中(在迁移文件夹中)添加属性 CommandTimeout = Int32.MaxValue;

回答by danmbuen

I restarted the SQL Server service (Win7 - Computer Management > Services and Applications > Services)

我重新启动了 SQL Server 服务(Win7 - 计算机管理 > 服务和应用程序 > 服务)

回答by Josh

For me, the problem was that that migration script took a long time to run (15 minutes).

对我来说,问题是迁移脚本需要很长时间才能运行(15 分钟)。

This is how I worked around the issue:
1. Run update-database -script(-forcemay be necessary)
2. Copy this SQL script output and run in SQL Server Management Studio

我是这样解决这个问题的:
1. 运行update-database -script-force可能是必要的)
2. 复制此 SQL 脚本输出并在 SQL Server Management Studio 中运行

回答by ransems

An FYI EF Migrations pull their timeout from a separate configuration:

仅供参考的 EF 迁移从单独的配置中提取超时:

public class MyContextConfiguration : DbMigrationsConfiguration<MyContext>
{
    public MyContextConfiguration()
    {
        CommandTimeout = 900;
    }
}

Change the 900 to a something higher, all of the other SQL timeout changes (web.config, etc.) did not do anything, this worked for me.

将 900 更改为更高的值,所有其他 SQL 超时更改(web.config 等)都没有做任何事情,这对我有用。