设置超时时,实体框架连接到Azure的 [英] Timeout when setting up Entity Framework connecting to Azure

查看:598
本文介绍了设置超时时,实体框架连接到Azure的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Azure数据库,并正在设置实体框架。我认为连接字符串是正确的...

 < configSections>
   <节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/>
< / configSections>
<&是connectionStrings GT;
     <添加名称=MyContext connectionString=\"Server=tcp:azure_server_name.database.windows.net,1433;Database=azure_database_name;User ID=azure_user_account@azure_server_name;Password=azure_password;Trusted_Connection=False;Encrypt=True;Connection超时= 30
          的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;

...但我不断收到以下超时错误。

 消息:发生了错误。
ExceptionMessage:在'ObjectContent`1类型没有序列化响应正文内容类型应用/ JSON的;字符集= utf-8'。
ExceptionType:System.InvalidOperationException,
堆栈跟踪:空,
的InnerException:{
   消息:发生了错误。
   ExceptionMessage:超时​​超时时间在操作完成或服务器没有响应之前已过。
   ExceptionType:System.Data.SqlClient.SqlException,
   堆栈跟踪:
    在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection,Action`1 wrapCloseInAction)\\ r \\ n
    在System.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,布尔breakConnection,Action`1 wrapCloseInAction)\\ r \\ n
    在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔callerHasConnectionLock,布尔asyncClose)\\ r \\ n
    在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,的SqlCommand cmdHandler,SqlDataReader的数据流,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,布尔和放大器; dataReady)\\ r \\ n
    在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(字符串methodName中,布尔异步,的Int32超时,布尔asyncWrite)\\ r \\ n
    在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成,字符串methodName中,布尔sendToPipe,超时的Int32,布尔asyncWrite)\\ r \\ n在System.Data.SqlClient.SqlCommand.ExecuteNonQuery(个)\\ r \\ n
    在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher< NonQuery> b__0(DbCommand和T,DbCommandInterceptionContext`1 C)\\ r \\ n
    在System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget目标,Func`3操作,TInterceptionContext interceptionContext,Action`3执行,执行Action`3)\\ r \\ n
    在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(的DbCommand命令,DbCommandInterceptionContext interceptionContext)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.<CreateDatabaseFromScript>b__19(DbConnection康恩)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()\\r\    在System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()\\r\    在System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult](Func`1操作)\\ r \\ n
    在System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(动作操作)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(SqlConnection的的DbConnection,Action`1行为)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(SqlConnection的的DbConnection,Action`1行为)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1的CommandTimeout,SqlConnection的的DbConnection,字符串createDatabaseScript)\\ r \\ n
    在System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(连接的DbConnection,Nullable`1的CommandTimeout,StoreItemCollection storeItemCollection)\\ r \\ n
    在System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(连接的DbConnection,Nullable`1的CommandTimeout,StoreItemCollection storeItemCollection)\\ r \\ n
    在System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase(个)\\ r \\ n
    在System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(连接的DbConnection)\\ r \\ n
    在System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(动作mustSucceedToKeepDatabase)\\ r \\ n
    在System.Data.Entity.Migrations.DbMigrator.Update(字符串targetMigration)\\ r \\ n
    在System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext,Func`3 createMigrator,ObjectContext的ObjectContext的)\\ r \\ n
    在System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext的ObjectContext的,DatabaseExistenceState existenceState)\\ r \\ n
    在System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)\\ r \\ n
    在System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext上下文)\\ r \\ n
    在System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()\\r\    在System.Data.Entity.Internal.InternalContext.PerformInitializationAction(动作动作)\\ r \\ n
    在System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization(个)\\ r \\ n
    在System.Data.Entity.Internal.LazyInternalContext&LT; InitializeDatabase&GT; b__4(InternalContext C)\\ r \\ n
    在System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput输入)\\ r \\ n
    在System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1动作)\\ r \\ n
    在System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase(个)\\ r \\ n
    在System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型的EntityType)\\ r \\ n
    在System.Data.Entity.Internal.Linq.InternalSet`1.Initialize(个)\\ r \\ n
    在System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator(个)\\ r \\ n
    在System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator(个)\\ r \\ n
    在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IEnumerable的值,JsonArrayContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n
    在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n
    在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter,对象的值,类型的objectType)\\ r \\ n
    在Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,对象的值,类型的objectType)\\ r \\ n
    在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型类型,对象的值,流writeStream,编码effectiveEncoding)\\ r \\ n
    在System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型类型,对象的值,流writeStream,编码effectiveEncoding)\\ r \\ n
    在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型类型,对象的值,流writeStream,HttpContent内容)\\ r \\ n
    在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型类型,对象的值,流writeStream,HttpContent内容,TransportContext transportContext,的CancellationToken的CancellationToken)\\ r \\ n ---从previous位置堆栈跟踪结束的地方例外被抛出--- \\ r \\ n
    在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)\\ r \\ n
    在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\\ r \\ n
    在System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()\",
   的InnerException:{
      消息:发生了错误。
      ExceptionMessage:等待操作超时
      ExceptionType:System.ComponentModel.Win32Exception,
      堆栈跟踪:空
   }}}**超时过期。之前,完成上述操作超时时间已过或服务器没有响应。**

我有在Azure防火墙打开我的IP地址......而且我通过调试运行此。

下面的C语言应该执行$ C $的点点......

 公共类MyContextInitializer:DropCreateDatabaseAlways&LT; MyContext&GT;
{
    保护覆盖无效的种子(MyContext上下文)
    {
        context.Database.CommandTimeout = 0;        VAR书=新的List&LT;图书&GT;
        {
            新图书(){名称=战争与皮斯,作者=托尔斯泰,价格=19.95米},
            新图书(){名称=我弥留之际,作者=福克纳,价格=99.95米},
            新图书(){名称=哈利波特1,作者=J.K.罗琳,价格=19.95米},
            新图书(){名称=临运8,作者=自由,价格=49.95米},
            新图书(){名称=书一,作者=作者1,价格=10.95米},
            新图书(){名称=第二册,作者=Author2,价格=20.95米},
            新图书(){名称=尚书三,作者=Author3,价格=30.95米}
        };
        books.ForEach(二= GT; context.Books.Add(B));
        context.SaveChanges();
        base.Seed(上下文);
    }
}

-----------------根据要求添加本书的结构和MyContext -------------------

 公共类图书
{
    公众诠释标识{搞定;组; }
    公共字符串名称{;组; }
    公共字符串作者{搞定;组; }
    公共十进制价格{搞定;组; }}
公共类MyContext:的DbContext
{
    公共MyContext():基地(NAME = MyContext)
    {    }    公共DbSet&LT;图书&GT;图书{搞定;组; }}


解决方案

简答

大约需要120秒SQL Azure中创建一个数据库。这就是为什么你超时。因此,增加的CommandTimeout 。一种方法是code一行放到你的的DbContext 构造。

 公共MyContext():基地(NAME = MyContext)
{
    //3分钟命令超时
    this.Database.CommandTimeout = 180;
}

故障排除步骤

我刚刚重新使用一个全新的SQL Azure的服务器在美国西部例外。当我打开Entity Framework的日志记录,输出显示,创建数据库语句导致超时。这里是日志输出。

 在2015年9月8日上午09时24分14秒-07打开的连接:00
SELECT CAST(SERVERPROPERTY('EngineEdition')为int)
- 执行在2015年9月8日上午9时24分14秒-07:00
- 完成40毫秒的结果:SqlDataReader的在2015年9月8日上午9点24分14秒-07关闭的连接:00
在2015年9月8日上午9时24分15秒-07打开的连接:00
IF DB_ID(N'mvp1')IS NOT NULL SELECT 1 ELSE SELECT COUNT(*)FROM sys.databases中WHERE [名] = N'mvp1
- 执行在2015年9月8日上午09时24分十五秒-07:00
- 完成306毫秒的结果:1在2015年9月8日上午9时24分15秒-07关闭的连接:00
在2015年9月8日上午9时24分15秒-07打开的连接:00
DROP DATABASE [mvp1]
- 执行在2015年9月8日上午09时24分十五秒-07:00
- 完成在10635毫秒,结果是:-1在2015年9月8日上午09时24分26秒-07关闭的连接:00
在2015年9月8日上午09时24分26秒-07打开的连接:00
创建数据库[mvp1]
- 执行在2015年9月8日上午9时24分26秒-07:00
- 无法在30050毫秒错误:超时过期。完成操作或服务器之前已超时期间没有响应。在2015年9月8日上午09点24分56秒-07关闭的连接:00

要进一步解决,我连接到​​SQL Azure数据库与SQL Server Management Studio并运行日志输出。该命令成功,但花的 1:53 以完成(只是两分钟)。这超出了默认的的DbContext 命令超时。

解决方法:增加的DbContext 命令超时超过这一期限。答对了。它的工作。

工作控制台应用程序上的我的电脑

packages.config

唯一的包是的EntityFramework 6.1.3版本。

 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT;套餐及GT;
  &LT;包ID =的EntityFramework版本=6.1.3targetFramework =net452/&GT;
&LT; /包&GT;

的App.config

此配置使用了拦截部分记录生成的T-SQL。这使我能够运行在SQL Server Management Studio中记录的T-SQL来确定需要多长时间来创建数据库。

 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT;结构&gt;
  &LT; configSections&GT;
    &lt;节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/&GT;
  &LT; / configSections&GT;
  &LT;&启动GT;
    &LT; supportedRuntime版本=V4.0SKU =.net框架,版本= v4.5.2/&GT;
  &LT; /启动&GT;
  &LT;&是connectionStrings GT;
    &LT;添加名称=MyContext
         的connectionString =服务器= TCP:d01kzjctcf.database.windows.net,1433;数据库= mvp1;用户ID = MVP @ d01kzjctcf;密码= 3PN * iV55XmtW; Trusted_Connection = FALSE;加密= TRUE;连接超时= 120;
         的providerName =System.Data.SqlClient的/&GT;
  &LT; /&是connectionStrings GT;
  &LT;&的EntityFramework GT;
    &LT; defaultConnectionFactory TYPE =System.Data.Entity.Infrastructure.SqlConnectionFactory,的EntityFramework/&GT;
    &LT;供应商&GT;
      &LT;供应商invariantName =System.Data.SqlClient的TYPE =System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer/&GT;
    &LT; /供应商&GT;
    &LT;&拦截器GT;
      &LT;拦截TYPE =System.Data.Entity.Infrastructure.Interception.DatabaseLogger,的EntityFramework&GT;
        &LT;&参数GT;
          &LT;参数值=C:\\ TEMP \\ LogOutput.txt/&GT;
        &LT; /参数&GT;
      &LT; /拦截&GT;
    &LT; /拦截&GT;
  &LT; /&的EntityFramework GT;
&LT; /结构&gt;

Program.cs的

演示简单地下降,创建数据库,书籍种子它,选择所有的书,和书的数量输出到控制台上。

 使用系统;
使用System.Data.Entity的;
使用System.Collections.Generic;
使用System.Data.Entity.SqlServer;公共类节目
{
    公共静态无效的主要()
    {
        Database.SetInitializer&所述; MyContext&GT;(新MyContextInitializer());
        变种数= 0;
        使用(VAR上下文=新MyContext())
        {
            数= context.Books.CountAsync()结果。
        }
        Console.WriteLine(的String.Format(有{0}的书。,计数));
        到Console.ReadLine();
    }
}公共类MyContextInitializer:DropCreateDatabaseAlways&LT; MyContext&GT;
{
    保护覆盖无效的种子(MyContext上下文)
    {
        context.Database.CommandTimeout = 0;        VAR书=新的List&LT;图书&GT;
        {
            新图书(){名称=战争与皮斯,作者=托尔斯泰,价格=19.95米},
            新图书(){名称=我弥留之际,作者=福克纳,价格=99.95米},
            新图书(){名称=哈利波特1,作者=J.K.罗琳,价格=19.95米},
            新图书(){名称=临运8,作者=自由,价格=49.95米},
            新图书(){名称=书一,作者=作者1,价格=10.95米},
            新图书(){名称=第二册,作者=Author2,价格=20.95米},
            新图书(){名称=尚书三,作者=Author3,价格=30.95米}
        };
        books.ForEach(二= GT; context.Books.Add(B));
        context.SaveChanges();
        base.Seed(上下文);
    }
}公共类MyContext:的DbContext
{
    公共MyContext():基地(NAME = MyContext)
    {
        this.Database.CommandTimeout = 180;
    }    公共DbSet&LT;图书&GT;图书{搞定;组; }
}公共类图书
{
    公众诠释标识{搞定;组; }
    公共字符串名称{;组; }
    公共字符串作者{搞定;组; }
    公共十进制价格{搞定;组; }
}

另请参见

在组数据库超时实体框架

<一个href=\"http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework\">How我查看由实体框架生成的SQL?

关闭思考

一个全球三分钟的CommandTimeout 可能只适合于发展。在生产中,你可能会想,以减少这或将其设置只对某些特定的长期运行的命令,如数据库的创建。

I have an Azure database and am setting up Entity Framework. I think the connection string is correct...

<configSections>
   <section name="entityFramework"   type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
     <add name="MyContext" connectionString="Server=tcp:azure_server_name.database.windows.net,1433;Database=azure_database_name;User ID=azure_user_account@azure_server_name;Password=azure_password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30"
          providerName="System.Data.SqlClient" />
</connectionStrings>

...but I keep getting the following timeout error.

"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException":{
   "Message":"An error has occurred.",
   "ExceptionMessage":"Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.",
   "ExceptionType":"System.Data.SqlClient.SqlException",
   "StackTrace":"   
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   
    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   
    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   
    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   
    at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)\r\n   
    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()\r\n   
    at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)\r\n   
    at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)\r\n   
    at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n   
    at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.<CreateDatabaseFromScript>b__19(DbConnection conn)\r\n  
    at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()\r\n   
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()\r\n   
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)\r\n   
    at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)\r\n   
    at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)\r\n   
    at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)\r\n   
    at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)\r\n   
    at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)\r\n   
    at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()\r\n   
    at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)\r\n   
    at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)\r\n   
    at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)\r\n   
    at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)\r\n   
    at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)\r\n   
    at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)\r\n   
    at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)\r\n   
    at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()\r\n   
    at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n   
    at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n   
    at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)\r\n   
    at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)\r\n 
    at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)\r\n   
    at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()\r\n   
    at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n   
    at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n   
    at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()\r\n   
    at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator()\r\n   
    at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   
    at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   
    at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   
    at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   
    at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   
    at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   
    at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   
    at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   
    at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
   "InnerException":{
      "Message":"An error has occurred.",
      "ExceptionMessage":"The wait operation timed out",
      "ExceptionType":"System.ComponentModel.Win32Exception",
      "StackTrace":null
   }}}

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

I do have the Azure Firewall open for my IP address...and I'm running this through the debugger.

Here's the little bit of code it should be executing...

public class MyContextInitializer : DropCreateDatabaseAlways<MyContext>
{
    protected override void Seed(MyContext context)
    {
        context.Database.CommandTimeout = 0;

        var books = new List<Book>
        {
            new Book() {Name = "War and Pease", Author = "Tolstoy",Price=19.95m },
            new Book() {Name = "As I Lay Dying", Author = "Faulkner",Price=99.95m },
            new Book() {Name = "Harry Potter 1", Author = "J.K. Rowling",Price=19.95m },
            new Book() {Name = "Pro Win 8", Author = "Liberty",Price=49.95m },
            new Book() {Name = "Book one", Author = "Author1",Price=10.95m },
            new Book() {Name = "Book two", Author = "Author2",Price=20.95m },
            new Book() {Name = "Book three", Author = "Author3",Price=30.95m }
        };
        books.ForEach(b => context.Books.Add(b));
        context.SaveChanges();
        base.Seed(context);
    }
}

-----------------Adding book structure and MyContext upon request-------------------

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public decimal Price { get; set; }

}


public class MyContext : DbContext
{
    public MyContext() : base("name=MyContext")
    {

    }

    public DbSet<Book> Books { get; set; }

}

解决方案

Short Answer

It takes about 120 seconds for SQL Azure to create a database. That is why you are timing out. So, increase the CommandTimeout. One way is to drop a single line of code into your DbContext constructor.

public MyContext() : base("name=MyContext")
{
    // three minute command timeout
    this.Database.CommandTimeout = 180;
}

Troubleshooting Steps

I just recreated the exception using a brand new SQL Azure server in West US. When I turned on Entity Framework logging, the output showed that the Create database statement caused the timeout. Here is the log output.

Opened connection at 9/8/2015 9:24:14 AM -07:00
select cast(serverproperty('EngineEdition') as int)
-- Executing at 9/8/2015 9:24:14 AM -07:00
-- Completed in 40 ms with result: SqlDataReader

Closed connection at 9/8/2015 9:24:14 AM -07:00
Opened connection at 9/8/2015 9:24:15 AM -07:00
IF db_id(N'mvp1') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'mvp1'
-- Executing at 9/8/2015 9:24:15 AM -07:00
-- Completed in 306 ms with result: 1

Closed connection at 9/8/2015 9:24:15 AM -07:00
Opened connection at 9/8/2015 9:24:15 AM -07:00
drop database [mvp1]
-- Executing at 9/8/2015 9:24:15 AM -07:00
-- Completed in 10635 ms with result: -1

Closed connection at 9/8/2015 9:24:26 AM -07:00
Opened connection at 9/8/2015 9:24:26 AM -07:00
create database [mvp1]
-- Executing at 9/8/2015 9:24:26 AM -07:00
-- Failed in 30050 ms with error: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Closed connection at 9/8/2015 9:24:56 AM -07:00

To troubleshoot further, I connected to the SQL Azure database with SQL Server Management Studio and ran the log output. The commands succeeded but took 1:53 to complete (just about two minutes). That exceeds the default DbContext command timeout.

The fix: increase the DbContext command timeout to exceed that duration. Bingo. It worked.

Working Console App on My Computer

packages.config

The only package is EntityFramework version 6.1.3.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net452" />
</packages>

App.config

This config uses the interceptors section to log the generated T-SQL. That enabled me to run the logged T-SQL on SQL Server Management Studio to determine how long it takes to create the database.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>    
    <add name="MyContext" 
         connectionString="Server=tcp:d01kzjctcf.database.windows.net,1433;Database=mvp1;User ID=mvp@d01kzjctcf;Password=3pN*iV55XmtW;Trusted_Connection=False;Encrypt=True;Connection Timeout=120;"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <interceptors>
      <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
        <parameters>
          <parameter value="C:\Temp\LogOutput.txt"/>
        </parameters>
      </interceptor>
    </interceptors>
  </entityFramework>
</configuration>

Program.cs

The demo simply drops and creates the database, seeds it with books, selects all the books, and outputs the number of books to the console.

using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;

public class Program
{
    public static void Main()
    {
        Database.SetInitializer<MyContext>(new MyContextInitializer());
        var count = 0;
        using (var context = new MyContext())
        {
            count = context.Books.CountAsync().Result;
        }
        Console.WriteLine(string.Format("There are {0} books.", count));
        Console.ReadLine();
    }
}

public class MyContextInitializer : DropCreateDatabaseAlways<MyContext>
{
    protected override void Seed(MyContext context)
    {
        context.Database.CommandTimeout = 0;

        var books = new List<Book>
        {
            new Book() {Name = "War and Pease", Author = "Tolstoy",Price=19.95m },
            new Book() {Name = "As I Lay Dying", Author = "Faulkner",Price=99.95m },
            new Book() {Name = "Harry Potter 1", Author = "J.K. Rowling",Price=19.95m },
            new Book() {Name = "Pro Win 8", Author = "Liberty",Price=49.95m },
            new Book() {Name = "Book one", Author = "Author1",Price=10.95m },
            new Book() {Name = "Book two", Author = "Author2",Price=20.95m },
            new Book() {Name = "Book three", Author = "Author3",Price=30.95m }
        };
        books.ForEach(b => context.Books.Add(b));
        context.SaveChanges();
        base.Seed(context);
    }
}

public class MyContext : DbContext
{
    public MyContext() : base("name=MyContext")
    {
        this.Database.CommandTimeout = 180;
    }

    public DbSet<Book> Books { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public decimal Price { get; set; }
}

See Also

Set database timeout in Entity Framework

How do I view the SQL generated by the entity framework?

Closing Thoughts

A global CommandTimeout of three minutes is probably appropriate only for development. In production, you will probably want to decrease that or to set it only for certain specific long-running commands such as database creation.

这篇关于设置超时时,实体框架连接到Azure的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆